Get IP address from socket descriptor?

后端 未结 4 1153
轻奢々
轻奢々 2021-01-19 03:06

I\'ve opened a TCP socket server (I\'ve omitted a few stuff, it is taken from here

sockfd = socket(p->ai_family, p->ai_socktype,
            p->ai_p         


        
相关标签:
4条回答
  • 2021-01-19 03:47

    If you want to know who's at the other end of your socket you can use getpeername in Linux. getsockname will tell you who you are. You decide what address you want your server to sit on initially though, at bind time.

    You may also find this SO question useful: bind socket to network interface

    And the book "Unix Network Programming, vol 1", by W. Richard Stevens.

    0 讨论(0)
  • 2021-01-19 03:53

    You can't use the socket to get the server's address before a client connects, because it isn't known.

    In principle, a host may have multiple IPs. The IP used for a connection to a server is the one belonging to the interface, through which the connection arrived. Until a connection arrives, it isn't known.
    Even if you have only one IP, connections may arrive from within the machine, in which case the address would be 127.0.0.1.

    So the listening socket has no information about the IP.
    You'll need to find what interfaces the machine has, and what's their IPs.

    0 讨论(0)
  • 2021-01-19 03:53

    The address of the server is the one that was passed to the successfull call to bind() (as shown in the source you linked).

    0 讨论(0)
  • 2021-01-19 04:02

    The address of the server is up to you.

    Depends on which parameters are passed to the bind() function.

    You can specify a single ip or bind your socket to every address of your host.

    Look at the Bind man page

    0 讨论(0)
提交回复
热议问题