简体   繁体   English

如何将sockaddr结构转换为sockaddr_in - C ++网络套接字ubuntu UDP

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

I am trying to get the client address, but i am unsure how do i cast the sockaddr structure to sockaddr_in? 我想获取客户端地址,但我不确定如何将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);

Thanks in advance! 提前致谢! :) :)


i've found questions that brought me to this step: Getting IPV4 address from a sockaddr structure 我发现问题让我走到了这一步: 从sockaddr结构中获取IPV4地址


Sorry to avoid confusion, this is my real implementation where "ci" is an object to store pointers such as sockaddr_in. 很抱歉为了避免混淆,这是我真正的实现,其中“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);

i will get the following errors: 我会收到以下错误:

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

I would point out that if this is actually C++ the idiomatic way to do this would be: 我想指出,如果这实际上是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();
}

This sample code handles IPv4 and IPv6 addresses and also would be considered more C++ idiomatic than either of the suggested implementations. 此示例代码处理IPv4和IPv6地址,并且还被认为比任何建议的实现都更加C ++惯用。

It is actually very simple! 它实际上非常简单!

struct sockaddr *sa = ...;

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

I think this will compile just fine for you and do what you want. 我认为这将为你编译得很好,并做你想要的。

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