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
Related
I wrote C code to control traffic lights between 2 raspberry Pi, and it works perfectly. However, I have a huge problem: I wrote all the code on my desktop computer and I wanted to change to my laptop. So I changed the IP address in my client, and now the TCP connection fails...
So I run my server.c first, and then my client.c, but after few seconds, I have the message "Connection failed". I really don't understand why, because it worked in my other computer with the same configuration. I give you only the code with the TCP connection.
Here is my code for the connection:
client.c:
/* TCP Variables*/
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *hello = "Hello from client";
char buffer[1024] = {0}; // message receive from RaspberryPI 1
void configurationTCP()
{
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, "192.168.137.193", &serv_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
}
}
int main()
{
// Start Message
printf("test!!\n");
// Enter Start Button
scanf("hey");
configureGPIOs();
launchTests();
// COnfigure TCP connection :
configurationTCP();
}
server.c:
void configurationTCP()
{
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
}
So I have been following this guide
http://www.binarytides.com/winsock-socket-programming-tutorial/
To create a simple tcp server in c, this is the code I came up with :
https://pastebin.com/CDxiLv3b
int c;
char client_message[2000];
int recv_size;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
printf("Could not create socket : %d", WSAGetLastError());
}
printf("Server Socket created.\n");
memset(&server_addr, 0, sizeof(server_addr));
//Prepare the sockaddr_in structure
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(port);
//Bind
if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d", WSAGetLastError());
}
printf("Bind to port %d done.\n", port);
//Listen to incoming connections
listen(server_socket, 3);
//Accept and incoming connection
puts("Waiting for incoming reverse shell...");
c = sizeof(struct sockaddr_in);
while ((client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &c)) != INVALID_SOCKET)
{
puts("Connection accepted");
if ((recv_size = recv(client_socket, client_message, 2000, 0)) == SOCKET_ERROR)
{
puts("recv failed");
break;
}
client_message[recv_size] = '\0';
strcpy_s(path, MAX_PATH_LEN, client_message);
break;
}
if (client_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d", WSAGetLastError());
return 1;
}
return 0;
(Yes I basicly copied and changed stuff)
Now the problem is that I can only connect to this server using the same connection I cant connect to it using diffrent computers in the network and even if I open port (which shouldn't actually matter) it wont accept the connection from the diffrent computers on my network (only from the same computer)
I just needed to open ports on the firewall
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
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.
I am writing a simple client and server program in C. I am able to send date from client to server. But, I am not able to send acknowledge from server to client.
/*******************udpserver.c*****************/
int main(int argc, char *argv[])
{
/* Variable and structure definitions. */
int sd, rc;
struct sockaddr_in serveraddr, clientaddr;
clientaddrlen = sizeof(clientaddr);
int serveraddrlen = sizeof(serveraddr);
char buffer[100];
char *bufptr = buffer;
int buflen = sizeof(buffer);
if((sd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("UDP server - socket() error");
exit(-1);
}
printf("UDP server - socket() is OK\n");
memset(&serveraddr, 0x00, serveraddrlen);
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(0);
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
if((rc = bind(sd, (struct sockaddr *)&serveraddr, serveraddrlen)) < 0) {
perror("UDP server - bind() error");
close(sd);
exit(-1);
}
int addr_len = sizeof(serveraddr);
if (getsockname(sd, (struct sockaddr *) &serveraddr, &addr_len)<0) {
perror("Error getting socket name.\n");
return -1;
}
printf("Using IP %s and port %d\n", inet_ntoa(serveraddr.sin_addr), ntohs(serveraddr.sin_port));
printf("UDP server - Listening...\n");
rc = recvfrom(sd, bufptr, buflen, 0, (struct sockaddr *)&clientaddr, &clientaddrlen);
if(rc < 0) {
perror("UDP Server - recvfrom() error");
close(sd);
exit(-1);
}
printf("UDP Server received the following:\n \"%s\" message\n", bufptr);
printf("UDP Server replying to the UDP client...\n");
rc = sendto(sd, bufptr, buflen, 0, (struct sockaddr *)&clientaddr, clientaddrlen);
if(rc < 0) {
perror("UDP server - sendto() error");
close(sd);
exit(-1);
}
printf("UDP Server - sendto() is OK...\n");
close(sd);
exit(0);
}
My UDPClient program:
/****************udpclient.c********************/
int main(int argc, char *argv[])
{
/* Variable and structure definitions. */
int sd, rc;
struct sockaddr_in serveraddr, clientaddr;
int serveraddrlen = sizeof(serveraddr);
char server[255];
char buffer[100];
char *bufptr = buffer;
int buflen = sizeof(buffer);
struct hostent *hostp;
memset(buffer, 0x00, sizeof(buffer));
/* 36 characters + terminating NULL */
memcpy(buffer, "Hello! A client request message lol!", 37);
if((sd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("UDP Client - socket() error");
exit(-1);
}
else
printf("UDP Client - socket() is OK!\n");
if(argc != 3) {
/*Use default hostname or IP*/
printf("UDP Client - Usage <Server hostname or IP>\n");
exit(0);
}
memset(&serveraddr, 0x00, sizeof(struct sockaddr_in));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(atoi(argv[2]));
hostp = gethostbyname(argv[1]);
if(hostp == (struct hostent *)NULL) {
printf("HOST NOT FOUND --> ");
printf("h_errno = %d\n", h_errno);
exit(-1);
}
else {
printf("UDP Client - gethostname() of the server is OK... \n");
printf("Connected to UDP server\n");
}
memcpy(&serveraddr.sin_addr, hostp->h_addr, sizeof(serveraddr.sin_addr));
rc = sendto(sd, bufptr, buflen, 0, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
if(rc < 0) {
perror("UDP Client - sendto() error");
close(sd);
exit(-1);
}
else
printf("UDP Client - sendto() is OK!\n");
printf("Waiting a reply from UDP server...\n");
rc = recvfrom(sd, bufptr, buflen, 0, (struct sockaddr *)&serveraddr, &serveraddrlen);
if(rc < 0) {
perror("UDP Client - recvfrom() error");
close(sd);
exit(-1);
} else {
printf("UDP client received the following: \"%s\" message\n", bufptr);
}
close(sd);
exit(0);
}
When running the two programs, I am getting the following output:
UdpServer:
$ ./UdpServer
UDP server - socket() is OK
Using IP 0.0.0.0 and port 49932
UDP server - Listening...
UDP Server received the following:
"Hello! A client request message lol!" message
UDP Server replying to the UDP client...
UDP Server - sendto() is OK...
UdpClient:
$ ./UdpClient MyPC 49932
UDP Client - socket() is OK!
UDP Client - gethostname() of the server is OK...
Connected to UDP server
UDP Client - sendto() is OK!
Waiting a reply from UDP server...
UdpClient program is stuck at this point. Could anyone please explain what the problem is?
You might like to use select() to make the process wait until data is avaibale for reading:
...
{
fd_set rfds;
int retval;
FD_ZERO(&rfds);
FD_SET(sd, &rfds);
retval = select(sd+1, &rfds, NULL, NULL, NULL);
if (retval == -1)
perror("select()");
else
printf("Data is available for reading now.\n");
...
}
...
If the server and client are running on the same machine, give
$ ./UdpClient localhost 49932
instead of
$ ./UdpClient MyPC 49932
else
$ ./UdpClient <server-IP-address> 49932
Also in the server code,
clientaddrlen = sizeof(clientaddr);
should be
int clientaddrlen = sizeof(clientaddr);
But I guess that's just a copy-paste mistake.