[英]How to get client IP by the socket number in C
I'm writing a simple client-server code in C. i was asked for the server to print the IP address of the client that connected to it. 我用C语言编写了一个简单的客户端-服务器代码。有人要求我打印与之连接的客户端的IP地址。 However, i can't seem to find a way to know the client's IP address from the server console. 但是,我似乎找不到从服务器控制台了解客户端IP地址的方法。 Is there a way to do that? 有没有办法做到这一点?
// Initialize Winsock.
if ( StartupRes != NO_ERROR )
{
printf( "error %ld at WSAStartup( ), ending program.\n", WSAGetLastError() );
// Tell the user that we could not find a usable WinSock DLL.
return;
}
/* The WinSock DLL is acceptable. Proceed. */
// Create a socket.
MainSocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( MainSocket == INVALID_SOCKET )
{
printf( "Error at socket( ): %ld\n", WSAGetLastError( ) );
return;
}
// Create a sockaddr_in object and set its values.
// Declare variables
Address = inet_addr(CHANNEL_IP);
if ( Address == INADDR_NONE )
{
printf("The string \"%s\" cannot be converted into an ip address. ending program.\n",
CHANNEL_IP);
return;
}
service.sin_family = AF_INET;
service.sin_addr.s_addr = Address;
service.sin_port = htons(clientinfo->senderPort);
//Bind the socket
bindRes = bind( MainSocket, ( SOCKADDR* ) &service, sizeof( service ) );
if ( bindRes == SOCKET_ERROR )
{
printf( "Channel-bind( ) failed with error %ld. Ending program\n", WSAGetLastError( ) );
return;
}
// Listen on the Socket.
ListenRes = listen( MainSocket, SOMAXCONN );
if ( ListenRes == SOCKET_ERROR )
{
printf( "Failed listening on socket, error %ld.\n", WSAGetLastError() );
return;
}
printf("Channel waiting for sender to connect...\n");
//Accepting connection
SenderSocket = accept( MainSocket, NULL, NULL );
if ( SenderSocket == INVALID_SOCKET ){
printf( "Accepting connection with client failed, error %ld\n", WSAGetLastError() ) ;
return;}
else
printf( "Sender Connected.\n" );
You need to pass in non-null values for the second and third parameters to accept
: 您需要为第二个和第三个参数传递非null值才能accept
:
struct sockaddr_in client_addr;
socklen_t slen = sizeof(client_addr);
SenderSocket = accept( MainSocket, (struct sockaddr *)&client_addr, &slen );
You can then get the client's IP and port from client_addr
. 然后,您可以从client_addr
获取客户端的IP和端口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.