error in client server udp c - c

I want to establish connection between two pc using client and server using C
I have been able to sent data from client and receive by server.
but when server want to sent data the error are appear in server side:
segmentation fail :11
here my program:
in client:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define MYPORT 4950
#define MAXBUFLEN 100
int main() {
char no[16], dt[30];
printf("‐‐‐‐‐ PROGRAM CHATTING ‐‐‐‐‐\n");
printf("To : ");
scanf("%s", no);
while(1){
printf("Me : ");
scanf("%s", dt); send(no, dt); receive();
}
}
int send(char no[], char dt[])
{
int sockfd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
struct hostent *he;
int addr_len, numbytes;
if((he = gethostbyname(no)) == NULL)
{
perror("gethostbyname");
exit(1);
}
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1)
{ //40
perror("socket");
exit(1);
}
their_addr.sin_family = AF_INET;
their_addr.sin_port = htons(MYPORT);
their_addr.sin_addr=*((struct in_addr*)he->h_addr);
memset(&(their_addr.sin_zero), '\0', 8);
if((numbytes=sendto(sockfd,dt,strlen(dt),0,(struct sockaddr*)&their_addr,sizeof(struct sockaddr)))==-1)
{
perror("sendto");
exit(1);
}
close(sockfd);
return 0;
}
int receive()
{
int sockfd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
struct hostent *he;
int addr_len, numbytes;
char buf[MAXBUFLEN];
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1) //68
{
perror("socket");
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(MYPORT);
my_addr.sin_addr.s_addr = INADDR_ANY; memset(&(my_addr.sin_zero),'\0',8);
if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1)
{
perror("bind");
exit(1);
}
addr_len = sizeof(struct sockaddr);
if((numbytes=recvfrom(sockfd,buf,MAXBUFLEN-1,0,(struct sockaddr *)&their_addr,&addr_len))==-1)
{
perror("recvfrom");
exit(1); }
buf[numbytes]='\0';
printf("%s : \"%s\"\n", inet_ntoa(their_addr.sin_addr), buf);
close(sockfd);
return 0;
}
and server:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define MYPORT 4950
#define MAXBUFLEN 100
char noip[50];
int main()
{
char no[16];
char dt[30];
printf("‐‐‐‐‐ PROGRAM CHATTING ‐‐‐‐‐\n");
receive();
strcpy (no, noip);
while(1){
printf("Me : ");
scanf("%s", dt);
send( dt);
receive();
}
}
int send(char dt[30]) {
int sockfd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
struct hostent *he;
int addr_len, numbytes;
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1){
perror("socket");
exit(1);
}
their_addr.sin_family = AF_INET;
their_addr.sin_port = htons(MYPORT);
their_addr.sin_addr=*((struct in_addr*)he->h_addr);
memset(&(their_addr.sin_zero), '\0', 8);
if((numbytes=sendto(sockfd,dt,strlen(dt),0,(struct sockaddr *)&their_addr,sizeof(struct sockaddr)))==-1)
{
perror("sendto");
exit(1); }
close(sockfd);
return 0; }
int receive() {
int sockfd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
struct hostent *he;
int addr_len, numbytes;
char buf[MAXBUFLEN];
char no[16];
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1){
perror("socket");
exit(1); }
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(MYPORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
memset(&(my_addr.sin_zero),'\0',8);
if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1){
perror("bind");
exit(1); }
addr_len = sizeof(struct sockaddr);
if((numbytes=recvfrom(sockfd,buf,MAXBUFLEN-1,0,(struct sockaddr *)&their_addr,&addr_len))==-1)
{
perror("recvfrom");
exit(1);}
buf[numbytes]='\0';
printf("%s : \"%s\"\n", inet_ntoa(their_addr.sin_addr), buf);
strcpy(no,inet_ntoa(their_addr.sin_addr));//copy data ke varibel no
close(sockfd);
return 0;
}
Any sugestion?

Do a debug build (option -g) and then call the gdb. It opens a prompt where you use
file "a.out"
to load the executable and afterwards call "run" to actually run you program under debugger's control. When the segfault happens, call "backtrace" and it should tell you the function and maybe the line where it happens.
But when I see the code, my first guess would be the input char array. Do you enter more than 29 characters when sending? ;)

Related

file transfer using stop and wait protocol and udp protocol in C

I want to send a file using UDP with stop and wait protocol. I have a client and server code that is working fine with a single input string.
I was trying to change the code for file transfer but no success. Can anyone help me with minimal changes to convert the below code for using file transfer?
code of client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
typedef struct packet{
char data[1024];
}Packet;
typedef struct frame{
int frame_kind; //ACK:0, SEQ:1 FIN:2
int sq_no;
int ack;
Packet packet;
}Frame;
int main(int argc, char **argv[]){
if (argc != 2){
printf("Usage: %s <port>", argv[0]);
exit(0);
}
int port = atoi(argv[1]);
int sockfd;
struct sockaddr_in serverAddr;
char buffer[1024];
socklen_t addr_size;
int frame_id = 0;
Frame frame_send;
Frame frame_recv;
int ack_recv = 1;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(port);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
while(1){
if(ack_recv == 1){
frame_send.sq_no = frame_id;
frame_send.frame_kind = 1;
frame_send.ack = 0;
printf("Enter Data: ");
scanf("%s", buffer);
strcpy(frame_send.packet.data, buffer);
sendto(sockfd, &frame_send, sizeof(Frame), 0, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
printf("[+]Frame Send\n");
}
int addr_size = sizeof(serverAddr);
int f_recv_size = recvfrom(sockfd, &frame_recv, sizeof(frame_recv), 0 ,(struct sockaddr*)&serverAddr, &addr_size);
if( f_recv_size > 0 && frame_recv.sq_no == 0 && frame_recv.ack == frame_id+1){
printf("[+]Ack Received\n");
ack_recv = 1;
}else{
printf("[-]Ack Not Received\n");
ack_recv = 0;
}
frame_id++;
}
close(sockfd);
return 0;
}
Code of server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
typedef struct packet{
char data[1024];
}Packet;
typedef struct frame{
int frame_kind; //ACK:0, SEQ:1 FIN:2
int sq_no;
int ack;
Packet packet;
}Frame;
int main(int argc, char** argv){
if (argc != 2){
printf("Usage: %s <port>", argv[0]);
exit(0);
}
int port = atoi(argv[1]);
int sockfd;
struct sockaddr_in serverAddr, newAddr;
char buffer[1024];
socklen_t addr_size;
int frame_id=0;
Frame frame_recv;
Frame frame_send;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(port);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
addr_size = sizeof(newAddr);
while(1){
int f_recv_size = recvfrom(sockfd, &frame_recv, sizeof(Frame), 0, (struct sockaddr*)&newAddr, &addr_size);
if (f_recv_size > 0 && frame_recv.frame_kind == 1 && frame_recv.sq_no == frame_id){
printf("[+]Frame Received: %s\n", frame_recv.packet.data);
frame_send.sq_no = 0;
frame_send.frame_kind = 0;
frame_send.ack = frame_recv.sq_no + 1;
sendto(sockfd, &frame_send, sizeof(frame_send), 0, (struct sockaddr*)&newAddr, addr_size);
printf("[+]Ack Send\n");
}else{
printf("[+]Frame Not Received\n");
}
frame_id++;
}
close(sockfd);
return 0;
}
Please help me. I am a beginner and taking references but not able to achieve.

Check if UDP port is open with ICMP in C

I am trying to check if a specific UDP port is open or not. I am trying to do this by sending UDP packets and checking the ICMP response to see if the UDP port is avaiable or not. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <pthread.h>
#include <arpa/inet.h> /* inet(3) functions */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/time.h>
#include <stdio.h>
#include <errno.h>
#define MAXLINE 10096
int main(int argc, char **argv)
{
int sockfd, portno;
struct sockaddr_in servaddr;
struct hostent *server;
int sendfd, recvfd;
server = gethostbyname(argv[1]);
if (server == NULL)
{
fprintf(stderr,"ERROR, no such host\n");
exit(EXIT_FAILURE);
}
//socket varibles
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&servaddr.sin_addr.s_addr, server->h_length);
//get port from command line arguments
portno = atoi(argv[2]);
servaddr.sin_port = htons(portno);
inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
// open send UDP socket
if((sendfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
{
perror("*** socket(,,IPPROTO_UDP) failed ***n");
exit(-1);
}
// open receive ICMP socket
if((recvfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0)
{
perror("*** socket(,,IPPROTO_ICMP) failed ***n");
exit(-1);
}
int n;
char sendline[] = "a message"; //string for message to be sent
char recvline[MAXLINE]; //string for message to be received
//send ping request
if(sendto(sendfd, sendline, sizeof(sendline), 0, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0)
{
perror("*** sendto() failed ***");
}
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 100000;
if (setsockopt(recvfd, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0) {
perror("Error");
}
n = recvfrom(recvfd, recvline, MAXLINE, 0, NULL, NULL);
recvline[n] = '\0'; /* null terminate */
struct iphdr *ip_hdr = (struct iphdr *)recvline;
int iplen = ip_hdr->ihl << 2;
struct icmphdr *icmp = (struct icmphdr *)((char *)ip_hdr + (4 * ip_hdr->ihl));
if((icmp->type == ICMP_UNREACH) && (icmp->code == ICMP_UNREACH_PORT))
{
printf("\nPORT CLOSED\n");
}
else
{
printf("\nPORT OPEN\n");
}
exit(0);
}
How can I get this working? When I run the code, It always says "PORT OPEN" in every port I test it with which definitely cannot be right.

Multithread server client C

Hello i have some problem with threads and client and server implementation, i created 2 clients that write on the socket infinite numbers.
to managed the 2 client in the sever.c i create threads everytime a new connection is accept.
it runs but if one client run it works but if i run the second one the first interrupted itself; how can i printf alternately ?
i would like : G1
G2
G1 etc
G1.
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <time.h>
void error(char *msg)
{
perror(msg);
exit(0);
}
struct message { //dichiarazione struct
time_t timestamp;
char g; //process identifier
int x;
};
int main(int argc, char *argv[])
{
int sockfd, portno, n,i;
struct message m1;
struct sockaddr_in serv_addr;
struct hostent *server;
struct timespec delay;
delay.tv_sec = 1;
delay.tv_nsec = 0; //in microseconds
long int offset=1000000;
struct timeval tv;
char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_UNIX;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
while(1){
m1.timestamp=time(NULL);
m1.x=i;
m1.g=getpid();
n = write(sockfd,&m1,sizeof(m1));
if (n < 0)
error("ERROR writing to socket");
i++;
delay.tv_nsec=offset+rand()%offset;
nanosleep(&delay,NULL);
}
return 0;
}`
R.c(server)
#include<stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include <arpa/inet.h>
#include <fcntl.h> // for open
#include <unistd.h> // for close
#include<pthread.h>
struct message { //dichiarazione struct
time_t timestamp;
char g; //process identifier
int x;
};
struct message client_message;
char buffer[1024];
static void * socketThread(void *arg)
{
while(1) {
int newSocket = *((int *)arg);
recv(newSocket , &client_message , sizeof(client_message), 0);
printf("message %d %d %ld\n",client_message.x,client_message.g,client_message.timestamp);
fflush(stdout);
sleep(1);
}
}
int main(){
int serverSocket, newSocket;
struct sockaddr_in serverAddr;
struct sockaddr_storage serverStorage;
socklen_t addr_size;
//Create the socket.
serverSocket = socket(AF_UNIX, SOCK_STREAM, 0);
// Configure settings of the server address struct
// Address family = Internet
serverAddr.sin_family = AF_UNIX;
//Set port number, using htons function to use proper byte order
serverAddr.sin_port = htons(6005);
//Set IP address to localhost
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
//Set all bits of the padding field to 0
memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
//Bind the address struct to the socket
bind(serverSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
//Listen on the socket, with 40 max connection requests queued
if(listen(serverSocket,50)!=0)
{
printf("Error\n");
return -1;
}
printf("Listening\n");
pthread_t tid[60];
int i = 0;
while(1)
{
//Accept call creates a new socket for the incoming connection
addr_size = sizeof serverStorage;
newSocket = accept(serverSocket, (struct sockaddr *) &serverStorage, &addr_size);
//for each client request creates a thread and assign the client request to it to process
//so the main thread can entertain next request
if( pthread_create(&tid[i], NULL, socketThread, &newSocket) != 0 )
printf("Failed to create thread\n");
else
++i;
}
return 0;
}
Thanks !
As I understand in server code in thread function socketThread() you get value of socket descriptor on each iteration. But when you accept new connection in this address writes new value of new socket descriptor. And after that each thread gets data only from last socket.
You should pass in socketThread() socket descriptor by value (not by a pointer)!

c TCP socket connection refused for localhost

I'm trying to make a client/server program in localhost but the client can not connect to the server and I do not know what I'm doing wrong.
I have tried to debug the program and all the parameters seem to be ok.The server does bind, connect, listen and accept.
With the client code a get connect: Invalid argument error. Client (I'm calling the client from the console with ./client localhost):
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char * argv[])
{
int cd;
struct hostent *hp;
struct sockaddr_in s_ain;
unsigned char byte;
hp = gethostbyname(argv[1]);
bzero((char *)&s_ain, sizeof(s_ain));
s_ain.sin_family = AF_INET;
memcpy(&(s_ain.sin_addr), hp->h_addr, hp->h_length);
s_ain.sin_port = htons(1025);
cd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if( connect(cd, (struct sockaddr*) &s_ain, sizeof(s_ain) == -1) ) {
fprintf(stderr, "connect: %s\n", strerror(errno));
return -1;
}
printf("%s\n", "IT WORKS!");
close(cd);
return 0;
}
Server:
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
int sd, cd;
socklen_t size;
unsigned char byte;
struct sockaddr_in s_ain, c_ain;
sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bzero((char *)&s_ain, sizeof(s_ain));
s_ain.sin_family = AF_INET;s_ain.sin_family = AF_INET;
s_ain.sin_addr.s_addr = INADDR_ANY;
s_ain.sin_port = htons(1025);
if(bind(sd, (struct sockaddr *)&s_ain, sizeof(s_ain)) == -1) {
fprintf(stderr, "%s\n", "err bind");
return -1;
}
if(listen(sd, 5) == -1) {
fprintf(stderr, "%s\n", "err listen");
return -1;
}
while(1) {
size = sizeof(c_ain);
cd = accept(sd, (struct sockaddr *)&c_ain, &size);
printf("%s\n", "IT WORKS !");
}
}
Either you have a typo in your example, or
if( connect(cd, (struct sockaddr*) &s_ain, sizeof(s_ain) == -1) ) {
fprintf(stderr, "%s\n", "err connect");
return -1;
}
has wrong parenthesis. Currently you will call connect with socklen_t addrlen as 0. It should read
if( connect(cd, (struct sockaddr*) &s_ain, sizeof(s_ain)) == -1) {
fprintf(stderr, "%s\n", "err connect");
return -1;
}
Some fixes in server.c
#include <netinet/in.h> // fix
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
int sd, cd;
unsigned char byte;
struct sockaddr_in c_ain;
sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bzero((char *)&c_ain, sizeof(c_ain));
c_ain.sin_family = AF_INET;
c_ain.sin_addr.s_addr = INADDR_ANY;
c_ain.sin_port = htons(1025);
bind(sd, (struct sockaddr *)&c_ain, sizeof(c_ain));
listen(sd, 5);
struct sockaddr_in t_ain;
while(1) {
int size = sizeof(t_ain); // < fix
cd = accept(sd, (struct sockaddr *)&t_ain, (socklen_t*)&size); // < fix
printf("%s\n", "IT WORKS !");
}
}
Also to test server you can use telnet:
telnet 127.0.0.1 1025

Socket Programming

I have a simple server and a client. I run the server at some port in my machine and when I try to connect my client to the server, it says network is unreachable. Can someone please suggest me why is it not being able to connect to the server. Please have a look at the files below:
server.c
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[]){
int sockfd, newsockfd, portno;
struct sockaddr_in serv_addr;
char sendmessage[50];
if(argc != 2){
fprintf(stderr, "ERROR, Port number not provided or Command line argument is not 2\n");
exit(1);
}
//creating a socket for the server
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0){
error("ERROR opening socket");
}
portno = atoi(argv[1]);
//describing the attributes for socket address
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if(bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0){
error("Error on binding the socket");
exit(1);
}
//allowing only 1 client to connect to the server at a time
if(listen(sockfd, 1) < 0){
error("Error in listening to the socket");
}
printf("Server is running...... \nWaiting for the connection from the client on port: %d\n", portno);
while(1){
//accepts the connection from the client
newsockfd = accept(sockfd, (struct sockaddr*)NULL, NULL);
if(newsockfd < 0){
error("Error on accepting");
}
strcpy(sendmessage, "Welcome to The Server");
write(newsockfd, sendmessage, strlen(sendmessage));
}
return 0;
}
client.c
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char* argv[]){
int sockfd;
char recvmessage[100];
char sendmessage[100];
int portno;
struct hostent *server;
struct sockaddr_in serv_addr;
if(argc != 3){
fprintf(stderr, "Error, either IP address or port number not provided.\n");
exit(1);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(socket < 0){
error("Error with creating a socket");
}
//check whether the host exist or not
server = gethostbyname(argv[1]);
if(server == NULL){
fprintf(stderr, "ERROR, the host is not defined\n");
exit(0);
}
//creating the socket
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
//connecting the client to the socket
if(connect(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0){
error("Could not connect to the server......");
exit(1);
}
printf("Connection Successful to the Server\n");
return 0;
}
First of all make sure you pass the same port number to both server & client. If the port number is different, communication between server and client won't happen.
Here is the code for local machine. You can change the code a little and pass IP addresses.
Server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define PORTNUM 2348
#define bufferLength 500
int main(int argc, char *argv[])
{
char buffer[bufferLength];
struct sockaddr_in dest; /* socket info about the machine connecting to us */
struct sockaddr_in serv; /* socket info about our server */
int mysocket; /* socket used to listen for incoming connections */
socklen_t socksize = sizeof(struct sockaddr_in);
memset(&serv, 0, sizeof(serv)); /* zero the struct before filling the fields */
serv.sin_family = AF_INET; /* set the type of connection to TCP/IP */
serv.sin_addr.s_addr = htonl(INADDR_ANY); /* set our address to any interface */
serv.sin_port = htons(PORTNUM); /* set the server port number */
mysocket = socket(AF_INET, SOCK_STREAM, 0);
/* bind serv information to mysocket */
bind(mysocket, (struct sockaddr *)&serv, sizeof(struct sockaddr));
/* start listening, allowing a queue of up to 1 pending connection */
listen(mysocket, 1);
int consocket;
int cpid;
while(1)
{
consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
perror("consocket\n");
if( (cpid = fork()) == 0 )
{
printf("inside child process\n\n\n");
close(mysocket);
close(consocket);
int recivedBytes = recv(consocket, buffer, bufferLength, 0);
buffer[recivedBytes] = '\0';
printf("recieved data %s \n", buffer);
return 0;
}
else
close(consocket);
}
close(mysocket);
return EXIT_SUCCESS;
}
Client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define MAXRCVLEN 500
#define PORTNUM 2348
int main(int argc, char *argv[])
{
char buffer[] = "My name is khan"; /* +1 so we can add null terminator */
int len, mysocket;
struct sockaddr_in dest;
mysocket = socket(AF_INET, SOCK_STREAM, 0);
memset(&dest, 0, sizeof(dest)); /* zero the struct */
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr("127.0.0.1"); /* set destination IP number */
dest.sin_port = htons(PORTNUM); /* set destination port number */
connect(mysocket, (struct sockaddr *)&dest, sizeof(struct sockaddr));
len = send(mysocket, buffer, strlen(buffer), 0);
perror("len\n");
/* We have to null terminate the received data ourselves */
buffer[len] = '\0';
printf("sent %s (%d bytes).\n", buffer, len);
close(mysocket);
return EXIT_SUCCESS;
}
Hope this helps

Resources