how to check that socket is active on TCP layer? - c

typedef unsigned int uint16;
SOCKET s, new_socket;
uint16 port =18001;
void CreateSocket()
{
WSADATA wsa;
struct sockaddr_in server; // creating a socket address structure: structure contains ip address and port number
printf("Initializing Winsock\n");
if(WSAStartup(MAKEWORD(2,2), &wsa)!=0)
{
printf("Failed Error Code: %d", WSAGetLastError());
return -1;
}
printf("Initialised\n");
//CREATING a SOCKET
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("Could not Create Socket\n");
//return 0;
}
printf("Socket Created\n");
server.sin_addr.s_addr = inet_addr("192.168.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(port);
//Binding between the socket and ip address
if(bind (s, (struct sockaddr *) &server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code: %d", WSAGetLastError());
}
puts("Bind Done");
//Listen to incoming connections
listen(s, 3);
//Accepting the incoming connection
new_socket = accept(s, NULL, NULL);
if (new_socket == INVALID_SOCKET)
{
printf(L"accept failed with error: %ld\n", WSAGetLastError());
closesocket(new_socket);
WSACleanup();
return 1;
}
else
printf("Client connected.\n");
closesocket(s);
}
int main()
{
CreateSocket();
return 0;
}
this is for TCP.
I am receiving a connection from the MASTER via the above ip address and port number, So I created a socket with port number and ip address for it. But how to check that the socket is active ?? how to check that the above socket code is valid (it's not showing any error). I am getting an error on the MASTER side saying that :
CONNECT EVENT CHECK FAILED (WSAGetLastError())
Could anyone help me in this ??

There is no connection between your socket and the address, you never bind() the address in server to the socket s.
Which, of course, is why your client fails to connect since the socket will not be using the expected port. I assume that you elsewhere call accept() and so on, to actually make the socket accept incoming connections, too.

Related

WinSock2 cant connect to simple server

I'm learning networking on windows using C and I get this weird 10038 error
WSADATA wsa;
SOCKET connect_socket;
printf("Initialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}printf("Initialised.\n");
if (connect_socket = socket(AF_INET, SOCK_STREAM, 0) == INVALID_SOCKET) {
printf("Could not create socket : %d\n", WSAGetLastError());
return -1;
}
printf("Socket created.\n");
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(80);
server.sin_addr.s_addr = inet_addr("142.250.184.196");
if (connect(connect_socket, (struct sockaddr*)&server, sizeof(server)) != 0)
{
printf("connect error : %d\n", WSAGetLastError());
return 1;
}
printf("Connected\n");
return 0;
nslookup www.google.com -> "142.250.184.196"
when trying to run program prints: "
Initialising Winsock...Initialised.
Socket created.
connect error : 10038"
if (connect_socket = socket(AF_INET, SOCK_STREAM, 0) == INVALID_SOCKET) {
Based on the operator precedence in C this means
connect_socket = (socket(AF_INET, SOCK_STREAM, 0) == INVALID_SOCKET)
Thus connect_socket is not the actual socket but the result of the check if the socket is valid. Assuming that socket creation worked then connect_socket will thus be false, i.e. 0.
Since 0 is not a valid TCP socket connect will fail with error 10038:
WSAENOTSOCK
10038
Socket operation on nonsocket.
An operation was attempted on something that is not a socket. Either the socket handle parameter did not reference a valid socket, or for select, a member of an fd_set was not valid.
To fix this, first assign to connect_socket, then compare with INVALID_SOCKET.

Receive data with UDP socket in VS2013

I wanted to receive an *.xml data by port 3702.
So I made a example Server. And sended data by three port 1500,2500,3702.(Edit the PORT in line 43)
It worked and printed data correctly from port 1500,2500.
But when I set the PORT to 3702.
it returned me a error:**Bind failed with error code :10048**
I found that maybe it existed other Client IP were sending data by PORT 3702 in my LAN.
How can I fix it?
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
#define BUFLEN 8192 //Max length of buffer
#define PORT 3702 //The port on which to listen for incoming data
int main()
{
SOCKET s;
struct sockaddr_in server, si_other;
int slen, recv_len;
char buf[BUFLEN];
WSADATA wsa;
slen = sizeof(si_other);
//Initialise winsock
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
printf("Initialised.\n");
//Create a socket
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)
{
printf("Could not create socket : %d", WSAGetLastError());
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(PORT);
//Bind
if (bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
puts("Bind done");
//keep listening for data
while (1)
{
printf("Waiting for data...");
fflush(stdout);
//clear the buffer by filling null, it might have previously received data
memset(buf, '\0', BUFLEN);
//try to receive some data, this is a blocking call
if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == SOCKET_ERROR)
{
printf("recvfrom() failed with error code : %d", WSAGetLastError());
//exit(EXIT_FAILURE);
}
//print details of the client/peer and the data received
printf("Received packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
printf("Data: %s\n", buf);
//now reply the client with the same data
}
closesocket(s);
WSACleanup();
return 0;
}
This is due to Address already in use.
Typically, only one usage of each socket address (protocol/IP address/port) is permitted. This error occurs if an application attempts to bind a socket to an IP address/port that has already been used for an existing socket, or a socket that was not closed properly, or one that is still in the process of closing. For server applications that need to bind multiple sockets to the same port number, consider using setsockopt (SO_REUSEADDR).
Client applications usually need not call bind at all - connect chooses an unused port automatically. When bind is called with a wildcard address (involving ADDR_ANY), a WSAEADDRINUSE error could be delayed until the specific address is committed. This could happen with a call to another function later, including connect, listen, WSAConnect, or WSAJoinLeaf.

how to check whether data is available on socket?

SOCKET s; // Create a SOCKET for listening for
// incoming connection requests.
SOCKET new_socket; // create a socket for accepting incoming connection
uint16 port =18001;
void CreateSocket()
{
int sin_size;
WSADATA wsa;
struct sockaddr_in server, master; // creating a socket address structure: structure contains ip address and port number
printf("Initializing Winsock\n");
if(WSAStartup(MAKEWORD(2,2), &wsa)!=0)
{
printf("Failed Error Code: %d", WSAGetLastError());
return -1;
}
printf("Initialised\n");
//CREATING a SOCKET
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("Could not Create Socket\n");
//return 0;
}
printf("Socket Created\n");
server.sin_addr.s_addr = inet_addr("192.168.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(port);
//Binding between the socket and ip address
if(bind (s, (struct sockaddr *) &server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code: %d", WSAGetLastError());
}
puts("Bind Done");
//Listen to incoming connections
listen(s, 3);
//Accepting the incoming connection
sin_size = sizeof(struct sockaddr_in);
new_socket = accept(s, (struct sockaddr *)&master, &sin_size);
printf("\n I got a connection from (%s , %d)",
inet_ntoa(master.sin_addr),ntohs(master.sin_port));
closesocket(new_socket);
/*new_socket = accept(s, NULL, NULL);
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error: %ld\n", WSAGetLastError());
closesocket(new_socket);
WSACleanup();
return 1;
}
else
printf("Client connected.\n");*/
}
I have created the socket and accepting the connection from the master but anyone tell me the condition for checking if there is any data available on the specified port number ?? I am using windows operating system. The above code is for creating socket for windows operating system.
how to make the above code to accept port number as an argument for sending and receiving data ??
You can easily find this online.
Assuming you are using winsock API, you just need to call recvfrom() - it will either return an error if there is some problem, or it will block until there is available incoming data.
See the documentation here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms740120%28v=vs.85%29.aspx

how to solve the socket connection?

SOCKET s; // Create a SOCKET for listening for
// incoming connection requests.
SOCKET new_socket; // create a socket for accepting incoming connection
uint16 port =18001;
void CreateSocket()
{
int sin_size;
WSADATA wsa;
struct sockaddr_in server, master; // creating a socket address structure: structure contains ip address and port number
printf("Initializing Winsock\n");
if(WSAStartup(MAKEWORD(2,2), &wsa)!=0)
{
printf("Failed Error Code: %d", WSAGetLastError());
//return -1;
}
printf("Initialised\n");
//CREATING a SOCKET
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("Could not Create Socket\n");
//return 0;
}
printf("Socket Created\n");
server.sin_addr.s_addr = inet_addr("192.168.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(port);
//Binding between the socket and ip address
if(bind (s, (struct sockaddr *) &server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code: %d", WSAGetLastError());
}
puts("Bind Done");
//Listen to incoming connections
listen(s, 3);
//Accepting the incoming connection
sin_size = sizeof(struct sockaddr_in);
new_socket = accept(s, (struct sockaddr *)&master, &sin_size);
printf("\n I got a connection from (%s , %d)",
inet_ntoa(master.sin_addr),ntohs(master.sin_port));
closesocket(s);
//new_socket = accept(s, NULL, NULL);
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error: %ld\n", WSAGetLastError());
closesocket(new_socket);
WSACleanup();
return 1;
}
else
printf("Client connected.\n");
I am creating a socket to accept a connection from the Master. When I see the traffic in the wireshark then it'sconnecting for the first time and the response will be sent as reset and later
the master will send and its repeating like this for some time. Why it is not connecting with the master for the first connect command ?
Wireshark output
1:request: 90 72.170764 192.168.0.1 192.168.0.2 TCP 18001 > 63789
[SYN, ACK] Seq=0 Ack=1 Win=8192 Len=0 MSS=1460 WS=8 SACK_PERM=1
2: response : 91 72.172839 192.168.0.2 192.168.0.1 TCP 63789 >
18001 [ACK] Seq=1 Ack=1 Win=65536 Len=0

Why server socket gives port no which is different from bound port no?

I am writing a small socket program in C. In server side I create a socket descriptor using socket() system call, then I am binding that socket with a port. After this I am trying to get the IP/Port no of the descriptor, it gives port no different then the bind port no. I am trying to get back IP/Port using getsockname() method, Is it right to use this method ? Please help me.
#define SERVER_ADDR "127.0.0.1"
#define SERVER_PORT "9090" // actual port no I am binding
#define QUEUE_LENGTH 10
int main()
{
struct addrinfo hints, *servinfo, *temp;
memset(&hints,0,sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
// here I am passing SERVER_PORT == 9090
int status = getaddrinfo(SERVER_ADDR,SERVER_PORT,&hints,&servinfo);
if(status != 0)
{
printf("Server: getaddrinfo() errored with code %d\n",status);
return;
}
int sfd = -1;
for(temp = servinfo; temp != NULL; temp = servinfo->ai_next)
{
sfd = socket(temp->ai_family,temp->ai_socktype,temp->ai_protocol);
if(sfd == -1)
{
printf("Server: Socket error with code %d\n",sfd);
continue;
}
status = bind(sfd,temp->ai_addr,temp->ai_addrlen);
if(status == -1)
{
printf("Server: Bind error with code %d\n",status);
continue;
}
printf("Server: Bind Successful\n");
// un necessary code goes here
struct sockaddr_in server_address;
char ipv4[INET_ADDRSTRLEN];
int addr_size = sizeof(server_address);
// i am using below method to get the port no from socket descriptor
getsockname(sfd, (struct sockaddr *)&server_address, &addr_size);
// I am expecting below will print 9090. but it prints different port no why ?
printf("Server Port: %d\n",server_address.sin_port);
printf("Port from getsddrinfo: %d\n",( (struct sockaddr_in *)temp->ai_addr)->sin_port);
inet_ntop(AF_INET, &(server_address.sin_addr),ipv4,INET_ADDRSTRLEN);
printf("Server IP Address: %s\n",ipv4);
// un necessary code ends here
break;
}
if(temp == NULL)
{
printf("Server: Failed to bind\n");
return;
}
status = listen(sfd,QUEUE_LENGTH);
if(status == -1)
{
printf("Server: Listening failed\n");
return;
}
printf("Server: waiting for coneections...\n");
while(1)
{
printf("Server: Main loop, will wait for client to connect...\n");
struct sockaddr client_address;
int addr_length = sizeof client_address;
// accepting client
int new_sfd = accept(sfd,&client_address,&addr_length);
}
printf("Server: Done!\n");
}
Output is:
Server: Bind Successful
Server Port: 33315 --> why this different from one I have binded (9090)
Port from getsddrinfo: 33315 --> why this different from one I have binded (9090)
Server IP Address: 127.0.0.1
Server: waiting for coneections...
Server: Main loop, will wait for client to connect...
The decimal members of struct sockaddr are returned in network byte order.
So you need to convert such values to host byte order, using the ntoh family of functions before using them, printing them.
add hints.sin_port = htons( 9090 );after hints.ai_socktype = SOCK_STREAM;

Resources