How to get ip address from sock structure in c?

后端 未结 3 1916
萌比男神i
萌比男神i 2020-12-02 20:06

I\'m writing simple server/client and trying to get client IP address and save it on server side to decide which client should get into critical section. I googled it severa

相关标签:
3条回答
  • 2020-12-02 20:41

    Assuming client_addr is a struct sockaddr_in (which it usually is). You can get the IP address (as a 32-bit unsigned integer) from client_addr.sin_addr.s_addr.

    You can convert it to a string this way:

    printf("%d.%d.%d.%d\n",
      int(client.sin_addr.s_addr&0xFF),
      int((client.sin_addr.s_addr&0xFF00)>>8),
      int((client.sin_addr.s_addr&0xFF0000)>>16),
      int((client.sin_addr.s_addr&0xFF000000)>>24));
    
    0 讨论(0)
  • 2020-12-02 20:47

    OK assuming you are using IPV4 then do the following:

    struct sockaddr_in* pV4Addr = (struct sockaddr_in*)&client_addr;
    struct in_addr ipAddr = pV4Addr->sin_addr;
    

    If you then want the ip address as a string then do the following:

    char str[INET_ADDRSTRLEN];
    inet_ntop( AF_INET, &ipAddr, str, INET_ADDRSTRLEN );
    

    IPV6 is pretty easy as well ...

    struct sockaddr_in6* pV6Addr = (struct sockaddr_in6*)&client_addr;
    struct in6_addr ipAddr       = pV6Addr->sin6_addr;
    

    and getting a string is almost identical to IPV4

    char str[INET6_ADDRSTRLEN];
    inet_ntop( AF_INET6, &ipAddr, str, INET6_ADDRSTRLEN );
    
    0 讨论(0)
  • 2020-12-02 20:54

    The easier and correct way for extracting IP address and port number would be:

    printf("IP address is: %s\n", inet_ntoa(client_addr.sin_addr));
    printf("port is: %d\n", (int) ntohs(client_addr.sin_port));
    

    The SoapBox's accepted answer won't be correct for all architectures. See Big and Little Endian.

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