I'm trying to get into socket programming with C and my problem is that no matter what I try I cannot get my client-server model to connect over the internet except through logging into my router and port forwarding the port I'm inputting in my program. Basically my server.c blocks and waits for a connection, then it sends the time of the server to the client once it connects. I've tried to open ports on both my machines like this:
sudo iptables -A INPUT -p tcp --dport 20001 -j ACCEPT
and I downloaded the iptables-persistent package that makes sure the rules stay on a reboot. iptables -L shows me that the ports are open on both machines, but the connection still times out. I know that somehow this is possible because Steam and Discord don't have to port forward anything and they still make it happen. I have a server at home so if the solution requires a 'middle man' server to facilitate a connection between two clients, then it won't be a problem for me. Also I am on two separate networks, so that's not the problem.
The server.c:
/* --- server.c --- */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
int main(int argc, char *argv[])
{
int listenfd = 0, connfd = 0;
struct sockaddr_in serv_addr;
char sendBuff[1025];
time_t ticks;
/* creates an UN-named socket inside the kernel and returns
* an integer known as socket descriptor
* This function takes domain/family as its first argument.
* For Internet family of IPv4 addresses we use AF_INET
*/
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));
memset(sendBuff, '0', sizeof(sendBuff));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(20001);
/* The call to the function "bind()" assigns the details specified
* in the structure 『serv_addr' to the socket created in the step above
*/
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
/* The call to the function "listen()" with second argument as 10 specifies
* maximum number of client connections that server will queue for this listening
* socket.
*/
listen(listenfd, 10);
while(1)
{
/* In the call to accept(), the server is put to sleep and when for an incoming
* client request, the three way TCP handshake* is complete, the function accept()
* wakes up and returns the socket descriptor representing the client socket.
*/
connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
/* As soon as server gets a request from client, it prepares the date and time and
* writes on the client socket through the descriptor returned by accept()
*/
ticks = time(NULL);
snprintf(sendBuff, sizeof(sendBuff), "%.24s\r\n", ctime(&ticks));
write(connfd, sendBuff, strlen(sendBuff));
close(connfd);
sleep(1);
}
}
and client.c:
/* --- client.c --- */
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int sockfd = 0, n = 0;
char recvBuff[1024];
struct sockaddr_in serv_addr;
if(argc != 2)
{
printf("\n Usage: %s <ip of server> \n",argv[0]);
return 1;
}
memset(recvBuff, '0',sizeof(recvBuff));
/* a socket is created through call to socket() function */
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(20001);
if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0)
{
printf("\n inet_pton error occured\n");
return 1;
}
/* Information like IP address of the remote host and its port is
* bundled up in a structure and a call to function connect() is made
* which tries to connect this socket with the socket (IP address and port)
* of the remote host
*/
if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
/* Once the sockets are connected, the server sends the data (date+time)
* on clients socket through clients socket descriptor and client can read it
* through normal read call on the its socket descriptor.
*/
while ( (n = read(sockfd, recvBuff, sizeof(recvBuff)-1)) > 0)
{
recvBuff[n] = 0;
if(fputs(recvBuff, stdout) == EOF)
{
printf("\n Error : Fputs error\n");
}
}
if(n < 0)
{
printf("\n Read error \n");
}
return 0;
}
This line is saying what port you're connecting to on the server
serv_addr.sin_port = htons(42020);
change it to the same port number as the server and it should work just fine.
serv_addr.sin_port = htons(20001);
#include <stdio.h>
#include "http.h"
#define MAX 4096
int main()
{
char s_msg[MAX], c_msg[MAX];
printf("%d", strlen(s_msg));
// Clean buffers:
memset(s_msg,'\0',sizeof(s_msg));
memset(c_msg,'\0',sizeof(c_msg));
char *msg = "GET / HTTP/1.1\r\nUser-Agent: Hellothere\r\nHost: HOSTNAME\r\n\r\n";
int soc = init_client();
int con = connection("HOSTNAME",80);
if(send(socket_desc, msg, strlen(msg), 0) < 0){
printf("Unable to send message\n");
return -1;
}
if (recv(socket_desc, c_msg , MAX, 0)<0)
{
printf("Failed to read from server\n");
return -1;
}
printf("Recieved from server : %s\n",c_msg);
return 0;
}
Using ngrok you need to use Host header
Related
I got an interview question in sockets in c programming
I got two files server.c and client.c
I was asked what will happen if you run a client when the server is not running : more specifically
run ./client localhost without running ./server in a different terminal
and I didn't know the answer (obviously it won't connect but what will happen I don't know)
they wanted an answer that was related to the sockets
when I checked in Wireshark to see if I can get some information I saw this:
the focus on the red record of the TCP sockets and the one record above it.
9999 is the port of the server
what is the meaning of every parameter here?
56020 ->9999 [SYN] Seq=0 Win=65495 Len=0 MSS=65495 SACK_PERM=1 TSval=736093598 TSecr=0 WS=128
and also what is the meaning of
9999 -> 56020 [RST, ACK] Seq=1 Ack=1 Win=0 Len=0
I tried to look for the meaning in google but didn't find results that related to sockets.
thank you very much in advanced!
code for the client.c
// to run in the terminal compile with
// gcc -o client client.c -Wall
// then run the following command:
// ./client localhost
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SIM_LENGTH 10
// #define IP_ADDRESS "127.0.0.1" // from the last part we put this in comment and resolve it with gethostbyname
#define PORT 9999
int main(int argc, char *argv[])
{
int sock;
struct sockaddr_in cli_name;
int count;
int value;
char *hostname;
char *hostaddr;
struct addrinfo *res;
struct sockaddr_in *saddr;
printf("Client is alive and establishing socket connection.\n");
printf("%d %s\n", argc, argv[1]);
if (argc != 2)
{
perror("Usage: hostnamelookup <hostname> error \n");
exit(1);
}
hostname = argv[1]; // hostname is the first argument
printf("Hostname is %s\n", hostname);
if (0 != getaddrinfo(hostname, NULL, NULL, &res)) // getaddrinfo is a function that returns a struct addrinfo* that
// contains a linked list of struct addrinfo (from nslookup.c)
{
fprintf(stderr, "Error in resolving hostname %s\n", hostname);
exit(1);
}
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
perror("Error opening channel");
close(sock);
exit(1);
}
saddr = (struct sockaddr_in *)res->ai_addr; // get the address of the server socket address structure (from nslookup.c)
hostaddr = inet_ntoa(saddr->sin_addr); // get the IP address of the server (from nslookup.c)
bzero(&cli_name, sizeof(cli_name));
cli_name.sin_family = AF_INET;
cli_name.sin_addr.s_addr = inet_addr(hostaddr); // set the IP address of the client (from nslookup.c)
cli_name.sin_port = htons(PORT);
if (connect(sock, (struct sockaddr *)&cli_name, sizeof(cli_name)) < 0)
{
perror("Error establishing communications");
close(sock);
exit(1);
}
for (count = 1; count <= SIM_LENGTH; count++)
{
read(sock, &value, 4);
printf("Client has received %d from socket.\n", value);
}
printf("Exiting now.\n");
close(sock);
exit(0);
}
server.c
// to run in the terminal compile with
// gcc -o server server.c -Wall
// then run the following command:
// ./server
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SIM_LENGTH 10
#define PORT 9999
int main(void)
{
int sock; // socket descriptor
int connect_sock; // socket descriptor for the connection
struct sockaddr_in serv_name; // server socket address structure
socklen_t len; // length of the socket address structure
int count; // number of bytes received
sock = socket(AF_INET, SOCK_STREAM, 0); // create a socket
// check if the socket is valid
if (sock < 0)
{
perror("Error opening channel");
exit(1);
}
// initialize the server socket address structure
bzero(&serv_name, sizeof(serv_name)); // clear the structure
serv_name.sin_family = AF_INET; // set the family to Internet
serv_name.sin_port = htons(PORT); // set the port number
// check if the bind is successful
if (bind(sock, (struct sockaddr *)&serv_name, sizeof(serv_name)) < 0) // bind the socket to the server address
{
perror("Error on binding");
exit(1);
}
// listen for connections
if (listen(sock, 1) < 0) // listen for connections on the socket
{
perror("Error on listening");
exit(1);
}
len = sizeof(serv_name); // get the length of the socket address structure
connect_sock = accept(sock, (struct sockaddr *)&serv_name, &len); // accept a connection on the socket
// check if the connection is valid
if (connect_sock < 0)
{
perror("Error on accepting");
exit(1);
}
for (count = 1; count <= SIM_LENGTH; count++) // loop to send the data
{
write(connect_sock, &count, 4); // send the data
printf("Server has written %d to socket.\n", count); // print the data
}
close(connect_sock); // close the connection
close(sock); // close the socket
}
If the host on that IP is completely down and unreachable (or the destination port is effectively firewalled), then the client will retry initiating the three way handshake a few times before timing out and bubbling up an error to the socket application calling connect.
If the host is up, but not listening on the expected port, it will send back an RST in response to receiving SYN from the client. That will effectively tell the client to "go away, I'm not listening". And the TCP stack will again bubble up an error to the socket application to trigger its connect call to return an error.
I have made one server and one client communicating through UDP sockets. The work that I am trying to do is that client will pass a string in the arguments and that string will be send to the server using UDP sockets. After receiving the string server will again echo(send) the string back to the client.Below are the codes for both:
code for echoClient.c :
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define MAXLINE 4096
int main(int argc, char const *argv[])
{
int sockfd;
struct sockaddr_in servAddr;
char sendLine[MAXLINE],recvLine[MAXLINE];
if(argc!=3)
{
printf("echoClient <Ip addr. of the server> <String to be echoed> \n");
exit(1);
}
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
printf("Error in creating the socket\n");
exit(2);
}
memset(&servAddr,0,sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(6565); // setting up the port
servAddr.sin_addr.s_addr = inet_addr(argv[1]); // using the given ip address of the server
printf("%s\n", argv[2]);
if((sendto(sockfd,(const char *)argv[2],strlen(argv[2]), MSG_CONFIRM,(struct sockaddr *) &servAddr, sizeof(servAddr))!=-1))
{
printf("data is sent to the server\n");
}
else
{
printf("can't send the data to the server\n");
exit(3);
}
int n = recvfrom(sockfd,(char * ) recvLine,MAXLINE,0,(struct sockaddr * )&servAddr,sizeof(servAddr));
if(n==-1)
{
printf("Can't receive the data from the server\n");
exit(4);
}
recvLine[n] = '\0'; // to terminate the received string
printf("%s\n",recvLine);
return 0;
}
code for echoServer.c:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define MAXLINE 4096
int main(int argc, char const *argv[])
{
int sockfd;
struct sockaddr_in servAddr,clientAddr;
char sendLine[MAXLINE],recvLine[MAXLINE];
if(argc!=1)
{
printf("echoServer\n");
exit(1);
}
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
printf("Error in creating the socket\n");
exit(2);
}
memset(&servAddr,0,sizeof(servAddr));
memset(&clientAddr,0,sizeof(clientAddr));
// filling the details of the server ip and port
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(6565);
servAddr.sin_addr.s_addr = INADDR_ANY; // using the given ip address of the server
if(bind(sockfd,(struct sockaddr * )&servAddr,sizeof(servAddr))<0)
{
printf("Binding of the socket failed\n");
exit(1);
}
printf("Server is Up... Waiting for the client...\n");
int len;
int n = recvfrom(sockfd,(char *) recvLine,MAXLINE,MSG_WAITALL,(struct sockaddr * )&clientAddr,&len);
if(n==-1)
{
printf("can't get the message from the client\n");
exit(2);
}
recvLine[n] = '\0';
printf("Message received from the client is %s\n",recvLine);
if(sendto(sockfd,(char *) recvLine,n,MSG_CONFIRM,(struct sockaddr *)&clientAddr,len)<0)
{
printf("can't send the message to the client\n");
exit(3);
}
return 0;
}
Now the actual problen is that when I am executing the above codes client is able to send the string to the server but server is unable to send the string back to the client.Server gives the error can't send the message to the client.
I am not able to figure out the error which is stopping the server to send the message to the client.Please help me with this.
I am running the echoClient.c with the command :
./a.out 127.0.0.1 hellofromclientside
In the server, you overlooked that the argument len to recvfrom() is a value-result argument, which before the call you have to initialize to the size of the clientAddr in order to get this address, so change
int len;
to
int len = sizeof clientAddr;
Similarly in the client, change
int n = recvfrom(sockfd,(char * ) recvLine,MAXLINE,0,(struct sockaddr * )&servAddr,sizeof(servAddr));
to
int len = sizeof servAddr;
int n = recvfrom(sockfd, recvLine, MAXLINE, 0, (struct sockaddr *)&servAddr, &len);
My socket server program is mentioned below. It works fine with the single client but when I try to connect it with another client at the same time, I am unable to connect. But I have defined MAX_CLIENTS in my program as 2 but still why I am unable to connect with multiple clients? What is the correct process to connect with multiple client? Will I be able to connect with multiple client by modifying this code? Any possible fix?
Socket Server Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <error.h>
#include <strings.h>
#include <unistd.h>
#include <arpa/inet.h>
#define ERROR -1
#define MAX_CLIENTS 2
#define MAX_DATA 1024
main (int argc, char **argv){
struct sockaddr_in server;
struct sockaddr_in client;
int sock;
int new;
int sockaddr_len = sizeof (struct sockaddr_in);
int data_len;
char data [MAX_DATA];
if ((sock = socket (AF_INET, SOCK_STREAM, 0)) == -1)
{
perror ("socket: ");
exit (-1);
}
printf("after socket");
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[2]));
server.sin_addr.s_addr = INADDR_ANY;
bzero (&server.sin_zero, 8);
printf("after server");
if ((bind (sock, (struct sockaddr*)&server, sockaddr_len)) == -1)
{
perror ("bind");
exit (-1);
}
printf("after bind");
if ((listen(sock, MAX_CLIENTS)) == ERROR)
{
perror ("listen");
exit (-1);
}
printf("after listen");
while(1)
{
if ((new = accept(sock, (struct sockaddr*)&client, &sockaddr_len)) == ERROR)
{
perror ("accept");
exit (-1);
}
printf("after new");
printf("New client connected from port no %d and IP %s\n",ntohs(client.sin_port), inet_ntoa(client.sin_addr));
data_len = 1;
while (data_len)
{
data_len = recv (new, data, MAX_DATA, 0);
if (data_len)
{
send (new, data, data_len, 0) ;
data [data_len]='\0';
printf("Sent mesg: %s", data);
}
printf("after datalen");
}
printf("Client Disconnected\n");
close(new);
}
printf("after close new");
close (sock);
}
Your program is single-threaded, and only does one thing at a time. When you have accepted a socket connection from a client (in your outer while loop) you start communicating with that client (in your inner while loop), and you don't get back to the accept call until the first client has disconnected.
Either use threads, with one thread that waits for new connections and one additional thread for each client, waiting for input from that client, or use the select call, which lets you wait for input simultaneously from several different sources.
I am reading a book on sockets in c and am making a very simple server program. I copied the code verbatim. There is nothing trying to connect to this server program yet and have change the port multiple times to make sure.
The program is failing on the accept method on the first run of the loop. From what I read in the man pages, accept is supposed to block the caller until a connection is made, and not fail if there aren't connections in the queue like it is doing. Is there any reason accept would be returning a value less than 0? I will post the code up to where it fails:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
//Max number of outstanding connection requests
#define MAXPEDNING 5
#define NONE
#define BUFSIZE 1024
int main(int argc, char **argv)
{
in_port_t servPort;
#ifdef CMDLINE
if(argc != 2)
{
puts("Error! Usage is <Server Port>");
return 0;
}
servPort = atoi(argv+1);
#endif //CMDLINE
#ifdef NONE
servPort = 2549;
#endif //NONE
int servSock;
if((servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
puts("socket() failed");
return 0;
}
struct sockaddr_in servAddr;
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(servPort);
printf("Port in network order: %d\nPort in host order:%d\n", servAddr.sin_port, ntohs(servAddr.sin_port));
if((bind(servSock, (struct sockaddr*) &servAddr, sizeof(servAddr)))<0)
{
puts("bind failed");
return 0;
}
while(1)
{
struct sockaddr_in clntAddr;
socklen_t clntAddrLen = sizeof(clntAddr);
int clntSock = accept(servSock, (struct sockaddr*) &clntAddr, &clntAddrLen);
if(clntSock < 0)
{
puts("accept failed");
return 0;
}
It reaches the accept failed and quits. The only thing that is odd about my setup is that I am on a Debian VM (VirtualBox) and I am wondering if network operations are handled in a weird way. I shouldn't be even trying to accept anything because there are no connections.
You need to call listen() in between bind() and accept().
I am using Ubuntu 12.05.I have been trying to implement Stop and wait protocol through C socket programming.I have created two programs,one featuring the server and other one the client. Expected working of the code is explained through comments
serversocket.c
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <error.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
int main(int argc,char *argv[])
{
int listenfd = 0,qlength=10,connfd = 0,t=5;
int n;
struct sockaddr_in serv;
struct sockaddr_in dest;
socklen_t socksize = sizeof(struct sockaddr_in);
char sendBuff[1024]="hi\n";
//time_t ticks;
listenfd = socket(AF_INET,SOCK_STREAM,0); //socket for listening to connection requests
memset(&serv,'0',sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = htonl(INADDR_ANY);
serv.sin_port=htons(5000);
bind(listenfd,(struct sockaddr *)&serv,sizeof(serv)); //binding the socket to a port
listen(listenfd,2);
connfd=accept(listenfd,(struct sockaddr *)&dest,&socksize); //another socket for sending and receiving on the previously built socket
while(connfd){
printf("Incoming connection from %s-sending a hi...\n",inet_ntoa(dest.sin_addr));
send(connfd,sendBuff,strlen(sendBuff),0); //at first my server sends a hi
sleep(3);
n=recv(connfd,sendBuff,1024,0); //if hi received by the client,then server should receive "Message Received" from the client
sendBuff[n]='\0';
printf("%s",sendBuff);
connfd=accept(listenfd,(struct sockaddr *)&dest,&socksize); }
return 0;
}
clientsocket.c
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int sockfd = 0, n = 0,m=2;
char recvBuff[1024];
struct sockaddr_in serv_addr;
if(argc != 2)
{
printf("\n Usage: %s <ip of server> \n",argv[0]);
return 1;
}
memset(recvBuff, '0',sizeof(recvBuff));
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000);
if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0)
{
printf("\n inet_pton error occured\n");
return 1;
}
if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
while(m--){ //m is 2 initially,I want that sending and receiving should be done 2 times
n = recv(sockfd,recvBuff,1024,0);
recvBuff[n]='\0'; //"hi" is received
printf("%s",recvBuff);
if(recvBuff=="hi\n")
send(sockfd,"Message Received",strlen("Message Received\n"),0);} //sending "Message received"
return 0;
}
Now sending messages from server to client works fine, but client to server(Message received) is creating problems.Neither it is giving an error, nor correct results,it just gives a blank screen.
You cannot compare strings using the "==" operator.
You need to use strcmp()
So....
if( strcmp( recvBuff, "hi\n" ) == 0 )
send(sockfd,"Message Received",strlen("Message Received\n"),0);
else
printf( "[%s] != [hi\n]\n", recvBuff );
Basically, you have three different issue in your code:
the string comparison (fixed by K Scott Piel).
The print of the received message are not coming out. You need to add '\n' in all your printf functions.
This is the most important issue: after the first communication between the server and the client, you are calling the accept function in the server code. From the man accept page, we can read
The accept() function shall extract the first connection on the
queue of pending connections, create a new socket with the same socket
type protocol and address family as the specified socket, and allocate
a new file descriptor for that socket.
So, after the first communication, your server is waiting for a new connection and your client is waiting for a message from the server. The second communication will never happen.
To solve this issue, you can use fork() API.
Here is a fix proposal using the fork():
clientsocket.c
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int sockfd = 0, n = 0,m=2;
char recvBuff[1024];
struct sockaddr_in serv_addr;
if(argc != 2)
{
printf("\n Usage: %s <ip of server> \n",argv[0]);
return 1;
}
memset(recvBuff, '0',sizeof(recvBuff));
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000);
if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0)
{
printf("\n inet_pton error occured\n");
return 1;
}
if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
//m is 2 initially,I want that sending and receiving should be done 2 times
while(m--)
{
printf("Waiting from the server ...\n");
n = recv(sockfd,recvBuff,1024,0);
recvBuff[n]= '\0'; //"hi" is received
printf("%s\n", recvBuff);
if(!strncmp(recvBuff, "hi\n", strlen("hi\n")))
{
printf("Send ACK\n");
n = send(sockfd,"Message Received",strlen("Message Received\n"),0);
printf("%d Sent ... \n", n);
}
} //sending "Message received"
return 0;
}
serversocket.c
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <error.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
int main(int argc,char *argv[])
{
int listenfd = 0,qlength=10,connfd = 0,t=5;
int n;
struct sockaddr_in serv;
struct sockaddr_in dest;
socklen_t socksize = sizeof(struct sockaddr_in);
char sendBuff[1024]="hi\n";
pid_t pid;
int m = 2;
//time_t ticks;
listenfd = socket(AF_INET,SOCK_STREAM,0); //socket for listening to connection requests
memset(&serv,'0',sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = htonl(INADDR_ANY);
serv.sin_port=htons(5000);
bind(listenfd,(struct sockaddr *)&serv,sizeof(serv)); //binding the socket to a port
printf("Server started ...\n");
listen(listenfd,2);
connfd=accept(listenfd,(struct sockaddr *)&dest,&socksize); //another socket for sending and receiving on the previously built socket
while(connfd > 0)
{
printf("Incoming connection from %s-sending a hi...\n",inet_ntoa(dest.sin_addr));
pid = fork();
if(pid) {
/* shall continue to listen to new client */
printf("Parent shall continue listening ... \n");
connfd=accept(listenfd,(struct sockaddr *)&dest,&socksize);
} else {
printf("Chlid process: Communication with the client ... \n");
while(m--)
{
printf("try %d - Sending %s ... \n", m, sendBuff);
send(connfd,sendBuff,strlen(sendBuff),0); //at first my server sends a hi
sleep(3);
n=recv(connfd, sendBuff, 1024, 0); //if hi received by the client,then server should receive "Message Received" from the client
sendBuff[n]='\0';
printf("Data received: [%s]\n", sendBuff); /* need to add '\n' so the print will be displayed */
strcpy(sendBuff, "hi\n");
}
printf("Child process will exit\n");
return 0;
}
}
return 0;
}