将字符串地址转换为套接字的IP地址调用

时间:2016-02-15 03:23:21

标签: c++ sockets udp gethostbyname

以下客户端代码正在尝试准备发送UDP数据报。 但是,地址设置不正确,因此发送无处可去。

我得到的错误是: sendto:多字节或宽字符无效或不完整

我认为这是在谈论地址,而不是正在发送的数据。

任何人都可以发现问题吗?

int sendSock; // socket for listening to other side (same for client and server)
struct sockaddr_in addr;
struct addrinfo* res = nullptr;

int initClient(const char hostname[], const char port[]) throw (Exception) {
    struct addrinfo hints;
    memset(&hints,0,sizeof(hints));
    hints.ai_family=AF_UNSPEC;
    hints.ai_socktype=SOCK_DGRAM;
    hints.ai_protocol=0;
    hints.ai_flags=AI_ADDRCONFIG;
    int err = getaddrinfo(hostname, port, &hints, &res);
    if (err != 0) {
      throw Exception(__LINE__, "failed to resolve remote socket address");
    }
    sendSock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if (sendSock < 0) { 
    throw Exception(__LINE__, strerror(errno));
    }

    struct hostent* hp = gethostbyname(hostname); // look up host name
    if (hp == nullptr) {
        throw Exception(__LINE__, "Can't find host");
    }

}

电话是:

    sendto(sendSock,buf,end, 0,res->ai_addr, res->ai_addrlen)

这是调试器中的addrinfo对象:

p *res
$5 = {ai_flags = 0, ai_family = 23, ai_socktype = 2, ai_protocol = 0, ai_addrlen = 28, ai_canonname = 0x0,
  ai_addr = 0x60003a660, ai_next = 0x60003a690}
 p *res->ai_addr
$6 = {sa_family = 23, sa_data = "\023\210", '\000' <repeats 11 times>}

我不认为正确的地址在那里,但沿途的呼叫都没有失败。

0 个答案:

没有答案