Networking & Sockets

a socket address and getaddrinfo/DNS

/ DNS -> DEE-EN-ESS, getaddrinfo -> get-ADDR-info /

When you tell the socket API where to connect or bind, you cannot just hand it the words 'example.com, port 80'. The kernel deals in numbers - a numeric IP address and a numeric port packed into a fixed structure. A socket address is that packed structure (a sockaddr), and the job of turning a human name like example.com into one is name resolution, done by DNS and wrapped for you by getaddrinfo().

The structure: bind() and connect() take a pointer to a struct sockaddr, which holds an address family (IPv4 or IPv6), a port, and an IP address, all in a fixed byte layout with the numbers in network byte order. In practice you rarely fill it by hand. Instead you call getaddrinfo("example.com", "80", &hints, &result), and it does two things: it consults DNS (the Domain Name System, the internet's distributed phone book that maps names to IP addresses) to find the IP, and it returns a ready-made list of sockaddr structures you can pass straight to connect(). It handles IPv4 versus IPv6 and multiple addresses for you, which is why modern code uses it instead of building addresses manually.

Why it matters: this is the bridge between the friendly names humans use and the numbers the network needs. Every time you type a domain name, something performs this lookup first. The modern advice is firm: use getaddrinfo() rather than older, IPv4-only helpers, because it is the one call that handles both IP versions, fills the sockaddr correctly, and frees you from worrying about byte order by hand. Remember a lookup can fail (name does not exist, no network) and can take time, so check its result like any other call.

struct addrinfo hints = {0}, *res; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; getaddrinfo("example.com", "80", &hints, &res); /* res now lists sockaddrs ready for connect(); free with freeaddrinfo(res) */ AF_UNSPEC means 'IPv4 or IPv6, whichever works'.

getaddrinfo() turns a name and port into ready-to-use sockaddrs, handling DNS and IP version for you.

DNS resolution is a separate network step that happens before you ever connect, and it can fail on its own (bad name, no DNS server). Remember to free the list with freeaddrinfo() to avoid a leak.

Also called
sockaddrname resolutionDomain Name System通訊端位址結構網域名稱系統