This is my two pieces of code:
server.c
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/timeb.h>
#include <string.h>
#include <unistd.h>
#define BYTES_NR 64
#define MSG_NR 512
int main(int argc, char *argv[]) {
char buf[BYTES_NR];
int sock,length;
struct sockaddr_in server,client;
int rval,i;
if(argc !=2) {
fprintf(stderr,"Usage: %s port\n",argv[0]);
exit(-1);
}
sock = socket(AF_INET,SOCK_DGRAM,0);
if(sock<0) {
perror("opening stream socket");
exit(1);
}
server.sin_family = AF_INET;
server.sin_addr.s_addr= INADDR_ANY;
server.sin_port = htons(atoi(argv[1]));
if (bind(sock,(struct sockaddr *)&server,sizeof(server))<0) {
perror("binding stream socket");
exit(1);
}
length = sizeof(server);
if(getsockname(sock,(struct sockaddr *)&server, (socklen_t *)&length)<0){
perror("getting socket name");
exit(1);
}
printf("Socket port #%d\n",ntohs(server.sin_port));
printf("test");
while(1) {
do {
printf("test2");
bzero(buf,sizeof(buf));
rval = recvfrom(sock,buf,sizeof(buf), 0, (struct sockaddr *)&client, (socklen_t *)&length );
if(rval<0)
perror("reading stream message");
i=0;
if(rval==0)
printf("Ending connection\n");
else {
printf("Message received: sending back\n");
strcat(buf,"*");
if (sendto(sock,buf,sizeof(buf),0,(struct sockaddr *)&client,sizeof(client))<0)
perror("writing on stream socket");
}
} while(rval !=0);
}
return 0;
}
client.c
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#define BYTES_NR 64
#define MSG_NR 512
int main(int argc, char *argv[]) {
char buf[BYTES_NR];
char buf2[BYTES_NR];
char msg[MSG_NR][BYTES_NR];
char answ[MSG_NR][BYTES_NR];
struct timeval xstime[MSG_NR];
struct timeval xftime[MSG_NR];
int i,sock,rval,length;
unsigned long delay;
struct sockaddr_in server,client;
struct hostent *hp, *gethostbyname();
if(argc !=3) {
fprintf(stderr,"Usage: %s servername serverport\n",argv[0]);
exit(-1);
}
for(i=0;i<MSG_NR;i++) {
sprintf(&msg[i][0],"%d",i);
}
sock= socket(AF_INET,SOCK_DGRAM,0);
if(sock<0) {
perror("opening stream socket");
exit(1);
}
client.sin_family= AF_INET;
client.sin_addr.s_addr = INADDR_ANY;
client.sin_port = htons(0);
if (bind(sock,(struct sockaddr *)&client,sizeof(client)) <0) {
perror("sending datagram message");
exit(1);
}
length= sizeof(client);
if(getsockname(sock,(struct sockaddr *)&server,(socklen_t *)&length)<0) {
perror("getting socket name");
exit(1);
}
printf("Socket port #%d\n",ntohs(client.sin_port));
hp = gethostbyname(argv[1]);
if (hp == 0) {
fprintf(stderr,"%s :unknow host",argv[1]);
exit(2);
}
bcopy( (char *)hp ->h_addr, (char *)&server.sin_addr,hp ->h_length);
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[2]));
for(i=0;i<MSG_NR;i++) {
printf("ciclo-");
strcpy(buf,msg[i]);
gettimeofday(&xstime[i],NULL);
if(sendto(sock, buf, sizeof(buf), 0, (struct sockaddr *)&server, sizeof(server)) < 0)
perror("sendto problem");
if((rval = read(sock,buf2,sizeof(buf2)))<0)
perror("reading stream message");
strcpy(answ[i],buf2);
gettimeofday(&xftime[i],NULL);
}
close(sock);
for (i=0; i<MSG_NR; i++) {
delay = (xftime[i].tv_sec-xstime[i].tv_sec)*1000000.+(xftime[i].tv_usec-xstime[i].tv_usec);
printf("msg %d [%s]: %0.3f ms\n",i,answ[i],delay/1000.);
}
return 0;
}
On the server side, why the printf that prints "test" does not operate before a client arrives with a request to send message? The same is true for the second printf that print "test2".
There's probably something conceptual that escapes me!
If i comment recv , the flow of execution returns normal.
This has nothing to do with recv. Change to:
printf("test\n");
By default, stdout is line-buffered, so you don't see anything until a newline is printed.
If you don't want to print a newline, you can use fflush(stdout); after each printf to print the current buffer. You can also use:
setvbuf(stdout, NULL, _IONBF, BUFSIZ);
to disable output buffering.
Related
I'm trying to send messages to a server, but when I connect, the server immediately fails receiving the message. It seems that the server "does not wait" for the user to type the message. The server is supposed to remain in that while loop, forever waiting for clients and printing their messages.
I have no idea what's wrong.
Server code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#define PORT 4000
#define WORD_SIZE 256
#define USER_SOCKETS 2
#define MAX_USERS 10
int receiveMessage(int socket, char message[])
{
int bytesReceived;
while (1)
{
bytesReceived = recv(socket, message, WORD_SIZE, 0);
if (bytesReceived < 0)
return -1;
if (bytesReceived == 0)
return 0;
}
}
int main(int argc, char *argv[])
{
int serverSockfd;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
if ((serverSockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
printf("Error creating the socket.\n");
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(serv_addr.sin_zero), 8);
if (bind(serverSockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("Error binding the socket..\n");
return -1;
}
if (listen(serverSockfd, 5) < 0)
{
printf("Error on listening.\n");
return -1;
}
int newSockfd;
while (1)
{
if (newSockfd = accept(serverSockfd, (struct sockaddr *)&cli_addr, &clilen) < 0)
{
printf("Error on accept a new client.\n");
continue;
}
char username[WORD_SIZE];
if (receiveMessage(newSockfd, username) < 0)
{
printf("Error receiving message.\n");
close(newSockfd);
}
printf("Message: %s\n", username);
close(newSockfd);
}
return 0;
}
Client code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define PORT 4000
int main(int argc, char * argv[]) {
int sockfd, n;
struct sockaddr_in serv_addr;
struct hostent * server;
char buffer[256];
if (argc < 2) {
fprintf(stderr, "usage %s hostname\n", argv[0]);
exit(0);
}
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr, "ERROR, no such host\n");
exit(0);
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
printf("ERROR opening socket\n");
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr = * ((struct in_addr * ) server -> h_addr);
bzero( & (serv_addr.sin_zero), 8);
if (connect(sockfd, (struct sockaddr * ) & serv_addr, sizeof(serv_addr)) < 0)
printf("ERROR connecting\n");
printf("Enter the message: ");
bzero(buffer, 256);
fgets(buffer, 256, stdin);
/* write in the socket */
n = write(sockfd, buffer, strlen(buffer));
if (n < 0)
printf("ERROR writing to socket\n");
bzero(buffer, 256);
printf("%s\n", buffer);
close(sockfd);
return 0;
}
The line:
if (newSockfd = accept(serverSockfd, (struct sockaddr *)&cli_addr, &clilen) < 0)
will set newSockfd to 0 if accept() succeeds, rather than to the descriptor of the socket. This is because < has a higher precedence than =, so the compiler behaves as-if you had written this:
if (newSockfd = (accept(serverSockfd, (struct sockaddr *)&cli_addr, &clilen) < 0))
You need to write this instead:
if ((newSockfd = accept(serverSockfd, (struct sockaddr *)&cli_addr, &clilen)) < 0)
I am implementing a simple server-client inter-process communication by sending data in binary format from the client to the server. The program is simple: it sends an unsigned number from 1 to 5, once at a time, in binary format. The server reads in the these binary data and converts it back to an unsigned int. However, when I tried to read in on the server size, my binary data was changing. How can I make the reading protocol to read in the data in a format that I sent. I appreciate all helps that I can get! Thank you.
Here is my implementation of the server:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <limits.h>
#include <netdb.h>
#define BUFFER_SIZE 10
int main(int argc, char *argv[])
{
int serv_sock, ret, data_socket;
socklen_t client_sock;
struct sockaddr_in serv_addr;
struct sockaddr_in client_addr;
// char buffer[BUFFER_SIZE];
uint32_t buffer = 0;
FILE *fp;
char hostname[HOST_NAME_MAX];
char ipaddr[INET_ADDRSTRLEN];
char port[6];
serv_sock = socket(AF_INET, SOCK_STREAM, 0);
if (serv_sock == -1)
{
perror("socket");
exit(1);
}
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(35000);
ret = bind(serv_sock, (const struct sockaddr *)&serv_addr, sizeof(serv_addr)); // bind socket to server address
if (ret == -1)
{
printf("bind error: %s\n", strerror(errno));
exit(1);
}
listen(serv_sock, 20);
// get hostname
gethostname(hostname, HOST_NAME_MAX);
// get ip address
getnameinfo((struct sockaddr *)&serv_addr, sizeof(serv_addr), ipaddr, INET_ADDRSTRLEN, port, 6, NI_NUMERICHOST | NI_NUMERICSERV);
// get port number
printf("Server %s is running on %s : %s\n", hostname, ipaddr, port);
while (1)
{
data_socket = accept(serv_sock, (struct sockaddr *)&client_addr, &client_sock);
// print client host name and ip address
getnameinfo((struct sockaddr *)&client_addr, sizeof(client_addr), hostname, HOST_NAME_MAX, port, 6, NI_NUMERICHOST | NI_NUMERICSERV);
printf("Client %s is connected to %s : %s\n", hostname, ipaddr, port);
if (data_socket == -1)
{
printf("accept error: %s\n", strerror(errno));
exit(1);
}
while (1){
int n = read(data_socket, &buffer, sizeof(uint32_t));
if (n == -1)
{
printf("read error: %s\n", strerror(errno));
exit(1);
}
if (n == 0)
{
break;
}
uint32_t temp = ntohl(buffer);
printf("%d\n", temp);
}
close(data_socket);
// if (!strncmp(buffer, "418", sizeof(buffer)))
// {
// break;
// }
}
close(serv_sock);
return 0;
}
Client implimentation:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <inttypes.h>
int main(int argc, char *argv[])
{
struct sockaddr_in addr;
int ret, data_socket, i;
unsigned int num_arr[5] = {1, 2, 3, 4, 5};
char send_str[100];
data_socket = socket(AF_INET, SOCK_STREAM, 0);
if (data_socket == -1)
{
perror("socket");
exit(1);
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(35000);
ret = connect(data_socket, (const struct sockaddr *)&addr, sizeof(addr));
if (ret == -1)
{
printf("connect error: %s\n", strerror(errno));
exit(1);
}
for (i = 0; i < 5; i++)
{
// sprintf(send_str, "%d\n", num_arr[i]);
// now send data as binary data
uint32_t num = htonl(num_arr[i]);
printf("%d\n", num);
printf("%d\n", ntohl(num));
write(data_socket, &num, sizeof(num));
write(data_socket, "\n", 1);
}
uint32_t delimiter = htonl(-1);
write(data_socket, &delimiter, sizeof(uint32_t));
if (argc == 2)
{
if (strncmp(argv[1], "quit", 4) == 0)
{
printf("User quits\n");
ret = write(data_socket, "418\n", 4);
}
else
{
printf("Wrong Argument\n");
}
}
close(data_socket);
return 0;
}
I made a simple Process-based parallel socket program.
My client code reaches the connect part and throws an Invalid argument error, and my server doesn't ouput anything. just cursor...
I split the terminal in two to run the code.
I run the code with:
gcc -o p-server p-server.c -Wall
./p-server
gcc -o p-client p-client.c -Wall
The output is
[C] Connecting...
[C] Can't connect to a Server: Invalid argument
p-server.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
//#include <sys/wait.h>
#define BUFFSIZE 4096
#define SERVERPORT 7799
int main(void){
int i, j, s_sock, c_sock;
struct sockaddr_in server_addr, client_addr;
socklen_t c_addr_size;
char buf[BUFFSIZE] = {0};
char hello[] = "Hello~ I am Server!\n";
//int option = 1;
//setsockopt(s_sock, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVERPORT);
server_addr.sin_addr.s_addr = inet_addr("10.0.0.131");
s_sock = socket(AF_INET, SOCK_STREAM, 0);
if (bind(s_sock, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1) {
perror("[S] Can't bind a socket");
exit(1);
}
if(listen(s_sock, 5)) {
perror("[S] Can't listen");
exit(1);
}
c_addr_size = sizeof(client_addr);
for ( i=0; i<3; i++) {
if ((c_sock = accept(s_sock, (struct sockaddr *) &client_addr, sizeof(client_addr))) == -1 ){
perror("[S] Can't accept a connection");
exit(1);
}
printf("[S] Connected: client IP addr=%s port=%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
//fork
switch(fork()){
case 0:
close(s_sock);
//1. say hello to client
if(send(c_sock, hello, sizeof(hello)+1, 0) == -1) {
perror("[S] Can't send message");
exit(1);
}
printf("[S] I said Hello to Client!\n");
//2. recv msg from client
if(recv(c_sock, buf, BUFFSIZE, 0) == -1) {
perror("[S] Can't receive message");
exit(1);
}
printf("[S] Client says: %s\n", buf);
exit(0);
}
close(c_sock);
}
/*
for(j=0; j<3; j++){
wait(&status);
printf("Patren waits %d\n"), wstatus;
}*/
}
p-client.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFFSIZE 4096
#define SERVERPORT 7799
int main(void){
int c_sock;
struct sockaddr_in server_addr;
socklen_t c_addr_size;
char buf[BUFFSIZE] = {0};
char hello[] = "Hi~I am Client!\n";
if((c_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVERPORT);
server_addr.sin_addr.s_addr = inet_addr("10.0.0.131");
printf("[C] Connecting...\n");
if (connect(c_sock, (struct sockaddr *) &server_addr, sizeof(server_addr) == -1)) {
perror("[C] Can't connect to a Server");
exit(1);
}
printf("[C] connected!\n");
//1. recv msg from server (maybe it's "hello")
if (recv(c_sock, buf, BUFFSIZE, 0) == -1) {
perror("[C] Can't receive message");
exit(1);
}
printf("[C] Server says: %s\n", buf);
//2. say hi to server
if(send(c_sock, hello, sizeof(hello)+1, 0) == -1) {
perror("[C] Can't send message");
exit(1);
}
printf("[C] I said Hi to Server!!\n");
printf("[C] I am going to sleep...\n");
sleep(10);
close(c_sock);
return 0;
}
I'm trying to send to the client the bits he has to read, then he has to read them. But for some reason he doesn't read the message, he only reads the bites,msgLength.I get the message form the server[server]The message was sent succefully.And the client is able to read only the msgLength, the msg is empty.
client:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <string.h>
#include <fcntl.h>
extern int errno;
int port;
int main(int argc, char *argv[])
{
int sd;
struct sockaddr_in server;
char msg[200];
int fd;
char msgLength[200];
if (argc != 3)
{
printf("Sintax: %s <adress_server> <port>\n", argv[0]);
return -1;
}
port = atoi(argv[2]);
if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("Error on socket().\n");
return errno;
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(argv[1]);
server.sin_port = htons(port);
if (connect(sd, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -1)
{
perror("[client]Erorr on connect().\n");
return errno;
}
if (recv(sd, msgLength, 2,0) < 0)
{
perror("[client]Erorr on recv() from the server.\n");
return errno;
}
bzero(msg,100);
if (recv(sd, msg, 22,0)<0){
perror("[client]Erorr on the second recv() from the server.\n");
return errno;
}
printf("msgLength: %s\n",msgLength);
printf("[client]The message recived is: %s\n", msg);
close(sd);
}
server:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/wait.h>
#define PORT 2024
extern int errno;
int main()
{
struct sockaddr_in server; r
struct sockaddr_in from;
char msg[100];
char msgrasp[100] = " ";
int sd;
pid_t pid;
if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("[server]Erorr on the socket().\n");
return errno;
}
bzero(&server, sizeof(server));
bzero(&from, sizeof(from));
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(PORT);
int optval = 1;
setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
setsockopt(sd, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
*/
if (bind(sd, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -1)
{
perror("[server]Erorr on the bind().\n");
return errno;
}
if (listen(sd, 5) == -1)
{
perror("[server]Erorr on listen().\n");
return errno;
}
while (1)
{
int client;
int length = sizeof(from);
printf("[server]We wait on the port %d...\n", PORT);
fflush(stdout);
client = accept(sd, (struct sockaddr *)&from, &length);
if (client < 0)
{
perror("[server]Erorr on accept().\n");
continue;
}
switch (pid = fork())
{
case -1:
perror("fork");
exit(1);
break;
case 0:
close(sd);
bzero(msg, 100);
printf("[server]Sending the text...\n");
fflush(stdout);
int fd1 = open("ToSend.txt", O_RDONLY);
char msgLength[100];
read(fd1, msgrasp, 100);
sprintf(msgLength,"%ld",strlen(msgrasp)+1);
printf("msgLength: %d\n",atoi(msgLength));
if ((send(client,msgLength,sizeof(msgLength),0) && send(client, msgrasp, atoi(msgLength),0)) <= 0)
{
perror("[server]Erorr on send() to the client.\n");
continue;
}
else
printf("[server]The message was sent succefully.\n");
exit(2);
default:
wait(NULL);
close(client);
break;
}
}
}
I solved it. The problem was that the server was sending sizeof(msgLength) witch is 100, and the client was reading just 2. If i replace sizeof(msgLength) with strlen(msgLength)+1 it works just fine. Thank you all for your time.
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