什么是客户端的客户端IP

时间:2014-01-29 08:30:02

标签: c++ c sockets tcp

有一种方法可以从客户端检索客户端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);

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

谢谢!

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

看这个代码dude

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

// Visual C ++ 5.0:cl getlocalip.cpp wsock32.lib

//此示例程序特此置于公共领域。

int doit(int,char **) {     char 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 main(int argc,char * argv []) {

WSAData wsaData;

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

    return 255;
}

int retval = doit(argc, argv);

WSACleanup();

return retval;

}