GetSockName and Getpeername functions

Source: Internet
Author: User

These 2 functions either return the local protocol address (GETSOCKNAME) associated with a socket, or return the address of the foreign protocol associated with a socket (getpeername)

int getsockname (int sockfd, struct sockaddr* localaddr, socklen_t * addrlen);

int getpeername (int sockfd, struct sockaddr * peeraddr, socklen_t * addrlen);

The last parameter of these 2 functions is the value-result parameter, which means that all 2 functions are loaded with the socket address structure referred to by the LOCALADDR and peeraddr pointers

Reasons to need these 2 functions:

1) on a TCP client that does not call bind, when Connect returns successfully, GetSockName is used to return the local IP address and local port number that the connection was given by the kernel

2) After calling bind with port number 0, GetSockName is used to return the local port number given by the kernel

3) GetSockName can be used to obtain an address cluster for a socket

4) on a server that calls bind at a wildcard IP address, once the connection to a client is established, getsockname can be used to return the local IP address to which the connection was given by the kernel

In such a call, the socket descriptor parameter must be a connected local IP, not a descriptor of the listening socket

5) When a server is called by a process calling exec to execute a program, the only way it can acquire a client's identity is to call Getpeername

All clients and servers start with the calling socket, which returns a socket descriptor

The customer then calls Connect

The server calls bind, listen, accept

Sockets typically use the standard close function to close

Most TCP servers are concurrent

They call fork for each pending client connection to derive a child process

Most UDP servers are iterative

GetSockName and Getpeername functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.