Skip to content

Commit

Permalink
Handle the various non-standard error codes that can be returned by g…
Browse files Browse the repository at this point in the history
…etaddrinfo() when throwing error messages, including printing the hostname and port on which binding was attempted.
  • Loading branch information
gwynne committed Feb 14, 2018
1 parent c4ad9d8 commit 60b2054
Showing 1 changed file with 36 additions and 3 deletions.
39 changes: 36 additions & 3 deletions Sources/TCP/Socket/TCPServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,11 @@ extension TCPSocket {

var res = getaddrinfo(hostname, port.description, &hints, &result)
guard res == 0 else {
throw TCPError.posix(
errno,
throw TCPError.gaierrno(
res,
identifier: "getAddressInfo",
possibleCauses: [
"The address that binding was attempted on does not refer to your machine."
"The address that binding was attempted on (\"\(hostname)\":\(port)) does not refer to your machine."
],
suggestedFixes: [
"Bind to `0.0.0.0` or to your machine's IP address"
Expand Down Expand Up @@ -165,3 +165,36 @@ extension TCPSocket {
}
}

extension TCPError {
static func gaierrno(
_ gaires: Int32,
identifier: String,
possibleCauses: [String] = [],
suggestedFixes: [String] = [],
file: String = #file,
function: String = #function,
line: UInt = #line,
column: UInt = #column
) -> TCPError {
guard gaires != EAI_SYSTEM else {
return .posix(
errno,
identifier: identifier,
possibleCauses: possibleCauses,
suggestedFixes: suggestedFixes,
file: file, function: function, line: line, column: column)
}
let message = COperatingSystem.gai_strerror(gaires)
let string = String(cString: message!, encoding: .utf8) ?? "unknown"
return TCPError(
identifier: identifier,
reason: string,
possibleCauses: possibleCauses,
suggestedFixes: suggestedFixes,
file: file,
function: function,
line: line,
column: column
)
}
}

0 comments on commit 60b2054

Please sign in to comment.