獲取外出介面
阿新 • • 發佈:2018-12-26
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)); }