2014-01-29 115 views
1

有一種方法可以從客戶端端檢索客戶端的IP地址嗎?什麼是客戶端的客戶端IP

客戶端:

int main(int argc, char *argv[]) 
{ 
    struct sockaddr_in serv_addr; 


    portno = atoi(argv[2]); //getting the server port from the terminal 
    sockfd = socket(AF_INET, SOCK_STREAM, 0); 

    server = gethostbyname(argv[1]); //getting the server IP from the terminal 

    bzero((char *) &serv_addr, sizeof(serv_addr)); 

    serv_addr.sin_family = AF_INET; 
    bcopy((char *)server->h_addr, 
    (char *)&serv_addr.sin_addr.s_addr,server->h_length); 
    serv_addr.sin_port = htons(portno); 

    connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr); 

    ....... 
    ...... 
} 

的感謝!

回答

1

getsockname(sockfd, ...)爲您提供連接套接字的「本地」地址。

實施例:

connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr); 

// Get the local socket address from the socket descriptor: 
struct sockaddr_storage sa; 
socklen_t salen = sizeof(sa); 
getsockname(sockfd, (struct sockaddr *)&sa, &salen); 

// Get numeric host and port from socket address as strings: 
char host[NI_MAXHOST]; 
char service[NI_MAXSERV]; 
getnameinfo((struct sockaddr *)&sa, salen, host, sizeof(host), service, sizeof(service), NI_NUMERICHOST|NI_NUMERICSERV); 

printf("local address: %s, local port: %s", host, service); 
0

看這個代碼哥們

//的Borland C++ 5.0:bcc32.cpp getlocalip.cpp

//的Visual C++ 5.0:CL getlocalip.cpp wsock32.lib

//此示例程序放置在公共領域。

int doit(int,char **) {acl ac [80];

if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR) { 

    cerr << "Error " << WSAGetLastError() << 

      " when getting local host name." << endl; 

    return 1; 
} 

cout << "Host name is " << ac << "." << endl; 

struct hostent *phe = gethostbyname(ac); 

if (phe == 0) { 
    cerr << "Yow! Bad host lookup." << endl; 
    return 1; 
} 

for (int i = 0; phe->h_addr_list[i] != 0; ++i) { 

    struct in_addr addr; 

    memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr)); 

    cout << "Address " << i << ": " << inet_ntoa(addr) << endl; 

} 

return 0; 

}

INT主(INT ARGC,CHAR *的argv []){

WSAData wsaData; 

if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) { 

    return 255; 
} 

int retval = doit(argc, argv); 

WSACleanup(); 

return retval; 

}

+0

謝謝:)我得到了它 – user1673206