簡體   English   中英

如何將sockaddr結構轉換為sockaddr_in - C ++網絡套接字ubuntu UDP

[英]how do you cast sockaddr structure to a sockaddr_in - C++ networking sockets ubuntu UDP

我想獲取客戶端地址,但我不確定如何將sockaddr結構轉換為sockaddr_in?

struct sockaddr_in cliAddr, servAddr;

    n = recvfrom(sd, msg, MAX_MSG, 0,(struct sockaddr *) cliAddr,sizeof(cliAddr));

 //i tried this but it does not work
    struct sockaddr cliSockAddr = (struct sockaddr *) cliAddr; 
    char *ip = inet_ntoa(cliSockAddr.sin_addr);

提前致謝! :)


我發現問題讓我走到了這一步: 從sockaddr結構中獲取IPV4地址


很抱歉為了避免混淆,這是我真正的實現,其中“ci”是存儲指針(如sockaddr_in)的對象。

    /* receive message */
    n = recvfrom(*(ci->getSd()), msg, MAX_MSG, 0,(struct sockaddr *) ci->getCliAddr(),ci->getCliLen());

    char *ip = inet_ntoa(ci->getCliAddr().sin_addr);

我會收到以下錯誤:

udpserv.cpp:166: error: request for member ‘sin_addr’ in ‘ci->clientInfo::getCliAddr()’, which is of non-class type ‘sockaddr_in*’

我想指出,如果這實際上是C ++,那么慣用的方法是:

sockaddr *sa = ...; // struct not needed in C++
char ip[INET6_ADDRSTRLEN] = {0};

switch (sa->sa_family) {
  case AF_INET: {
    // use of reinterpret_cast preferred to C style cast
    sockaddr_in *sin = reinterpret_cast<sockaddr_in*>(sa);
    inet_ntop(AF_INET, &sin->sin_addr, ip, INET6_ADDRSTRLEN);
    break;
  }
  case AF_INET6: {
    sockaddr_in6 *sin = reinterpret_cast<sockaddr_in6*>(sa);
    // inet_ntoa should be considered deprecated
    inet_ntop(AF_INET6, &sin->sin6_addr, ip, INET6_ADDRSTRLEN);
    break;
  }
  default:
    abort();
}

此示例代碼處理IPv4和IPv6地址,並且還被認為比任何建議的實現都更加C ++慣用。

它實際上非常簡單!

struct sockaddr *sa = ...;

if (sa->sa_family == AF_INET)
{
    struct sockaddr_in *sin = (struct sockaddr_in *) sa;
    ip = inet_ntoa(sin->sin_addr);
}

我認為這將為你編譯得很好,並做你想要的。

struct sockaddr_in cliAddr={}, servAddr={};

socklen_t cliAddrLength = sizeof(cliAddr);

n = recvfrom(sd, msg, MAX_MSG, 0,(struct sockaddr *)&cliAddr, &cliAddrLength);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM