p Common uses of this function are as follows: l -bullet t When .Xr bind 2 is called with a port number of 0 (indicating the kernel should pick an ephemeral port) .Fn getsockname is used to retrieve the kernel-assigned port number. t When a process calls .Xr bind 2 on a wildcard IP address, .Fn getsockname is used to retrieve the local IP address for the connection. t When a function wishes to know the address family of a socket, .Fn getsockname can be used. .El
p .Fn getsockname takes three parameters:
p .Fa s , Contains the file descriptor for the socket to be looked up.
p .Fa name points to a .Li sockaddr structure which will hold the resulting address information. Normal use requires one to use a structure specific to the protocol family in use, such as .Li sockaddr_in (IPv4) or .Li sockaddr_in6 (IPv6), cast to a (struct sockaddr *).
p For greater portability (such as newer protocol families) the new structure sockaddr_storage exists. .Li sockaddr_storage is large enough to hold any of the other sockaddr_* variants. On return, it should be cast to the correct sockaddr type, according to the current protocol family.
p .Fa namelen indicates the amount of space pointed to by .Fa name , in bytes. Upon return, .Fa namelen is set to the actual size of the returned address information.
p If the address of the destination socket for a given socket connection is needed, the .Xr getpeername 2 function should be used instead.
p If .Fa name does not point to enough space to hold the entire socket address, the result will be truncated to .Fa namelen bytes. .Sh RETURN VALUES On success, .Fn getsockname returns a 0, and .Fa namelen is set to the actual size of the socket address returned in .Fa name . Otherwise, .Va errno is set, and a value of -1 is returned. .Sh ERRORS The call succeeds unless: l -tag -width Er t Bq Er EBADF The argument .Fa s is not a valid descriptor. t Bq Er EFAULT The .Fa name parameter points to memory not in a valid part of the process address space. t Bq Er EINVAL The socket has been shut down. t Bq Er ENOBUFS Insufficient resources were available in the system to perform the operation. t Bq Er ENOTCONN The socket is not connected. t Bq Er ENOTSOCK The argument .Fa s is a file, not a socket. .El .Sh SEE ALSO .Xr bind 2 , .Xr socket 2 .Sh HISTORY The .Fn getsockname function call appeared in x 4.2 .