getsockname : 获取本机socket信息 ( 源ip/port)

void get_out_int(char * ipaddr,unsigned short port)
{
    //windows 初始化一下;
    //WSADATA wsadata;
    // WSAStartup(MAKEWORD(2, 2), &wsadata);

    SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0); // SOCK_STREAM 一样
    SOCKADDR_IN sock_addr,local_addr;
    memset(&local_addr, 0, sizeof(local_addr));
    memset(&sock_addr, 0, sizeof(sock_addr));
    sock_addr.sin_addr.s_addr = inet_addr(ipaddr); 
    sock_addr.sin_port = htons(port);
    sock_addr.sin_family = AF_INET;
    if (connect(sock, (SOCKADDR*)&sock_addr, sizeof(sock_addr)) == SOCKET_ERROR) 
    {
        print_error(WSAGetLastError());
        closesocket(sock);
        return;
    }
    int len = sizeof(local_addr);
    getsockname(sock, (SOCKADDR*)&local_addr, &len); //获取套接字源信息
    closesocket(sock);
    printf("local addr:%s\n", inet_ntoa(local_addr.sin_addr));
}

dashoumeixi
15 声望1 粉丝

下一篇 »
多播

引用和评论

0 条评论