I programmed client and server codes. Both client and server have two interfaces and two separate IP addresses. To check the result, i made two tap loopbacks.
And then, i check the server and client. It seems that client is sending packets over both sockets but server only receives packets from one socket.
Could you please guide me what is the problem with my code or maybe the loopbaks?
client
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <iostream>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#define BUFLEN 2048
#define MSGS 5 /* number of messages to send */
int main(void)
{
struct sockaddr_in myaddr, remaddr;
int fd, i, slen=sizeof(remaddr);
char buf[BUFLEN]; /* message buffer */
int recvlen; /* # bytes in acknowledgement message */
char *server = "192.168.10.10"; /* change this to use a different server */
//////////////////////////////////
struct sockaddr_in myaddr2, remaddr2;
int fd2, slen2=sizeof(remaddr2);
char buf2[BUFLEN]; /* message buffer */
int recvlen2; /* # bytes in acknowledgement message */
char *server2 = "192.168.11.11"; /* change this to use a different server */
//////////////////////////////
/* create a socket */
if ((fd=socket(AF_INET, SOCK_DGRAM, 0))==-1)
printf("socket created\n");
/////////////////////////////
if ((fd2=socket(AF_INET, SOCK_DGRAM, 0))==-1)
printf("socket2 created\n");
/////////////////////////////
/* bind fd and fd2 */
memset((char *)&myaddr, 0, sizeof(myaddr));
myaddr.sin_family = AF_INET;
//myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
inet_pton(AF_INET, "192.168.10.10", &myaddr.sin_addr.s_addr);
myaddr.sin_port = htons(2000);
/////////////////////////////
memset((char *)&myaddr2, 0, sizeof(myaddr2));
myaddr2.sin_family = AF_INET;
//myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
inet_pton(AF_INET, "192.168.11.11", &myaddr2.sin_addr.s_addr);
myaddr2.sin_port = htons(2001);
/////////////////////////////
if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
perror("bind failed");
return 0;
}
/////////////////////////////
if (bind(fd2, (struct sockaddr *)&myaddr2, sizeof(myaddr2)) < 0) {
perror("bind2 failed");
return 0;
}
/////////////////////////////
// printf("binding ip %s to port %d\n", myaddr.sin_addr.s_addr, myaddr.sin_port);
/* now define remaddr, the address to whom we want to send messages */
/* For convenience, the host address is expressed as a numeric IP address */
/* that we will convert to a binary format via inet_aton */
memset((char *) &remaddr, 0, sizeof(remaddr));
remaddr.sin_family = AF_INET;
remaddr.sin_port = htons(3000);
if (inet_aton(server, &remaddr.sin_addr)==0) {
fprintf(stderr, "inet_aton() failed\n");
exit(1);
}
/////////////////////////////
memset((char *) &remaddr2, 0, sizeof(remaddr2));
remaddr2.sin_family = AF_INET;
remaddr2.sin_port = htons(4000);
if (inet_aton(server2, &remaddr2.sin_addr)==0) {
fprintf(stderr, "inet_aton2() failed\n");
exit(1);
}
/////////////////////////////
/* now let's send the messages */
for (i=0; i < MSGS; i++) {
printf("Sending packet %d to %s port %d\n", i, server, remaddr.sin_port);
sprintf(buf, "This is packet %d", i);
if (sendto(fd, buf, strlen(buf), 0, (struct sockaddr *)&remaddr, slen)==-1) {
perror("sendto");
exit(1);
}
printf("socket %i SENT A PACKET \n", fd);
printf("Sending packet %d to %s port %d\n", i, server2, remaddr2.sin_port);
sprintf(buf2, "This is packet %d", i);
if (sendto(fd2, buf2, strlen(buf2), 0, (struct sockaddr *)&remaddr2, slen2)==-1) {
perror("sendto2");
exit(1);
}
printf("socket %i SENT A PACKET \n", fd2);
}
close(fd);
close(fd2);
return 0;
}
server
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>
#include <iostream>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define BUFSIZE 2048
int
main(int argc, char **argv)
{
int n;
fd_set readfds;
struct timeval tv;
struct sockaddr_in myaddr; /* our address */
struct sockaddr_in remaddr; /* remote address */
socklen_t addrlen = sizeof(remaddr); /* length of addresses */
int recvlen; /* # bytes received */
int fd; /* our socket */
unsigned char buf[BUFSIZE]; /* receive buffer */
/////////////////////
struct sockaddr_in myaddr2; /* our address */
struct sockaddr_in remaddr2; /* remote address */
socklen_t addrlen2 = sizeof(remaddr2); /* length of addresses */
int recvlen2; /* # bytes received */
int fd2; /* our socket */
unsigned char buf2[BUFSIZE]; /* receive buffer */
/////////////////////
/* create a UDP socket */
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("cannot create socket\n");
return 0;
}
printf("socket %i is open \n", fd);
///////////////////////////////
if ((fd2 = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("cannot create socket2\n");
return 0;
}
printf("socket %i is open \n", fd2);
///////////////////////////////
// clear the set ahead of time
FD_ZERO(&readfds);
// add our descriptors to the set
FD_SET(fd, &readfds);
FD_SET(fd2, &readfds);
// since we got s2 second, it's the "greater", so we use that for
// the n param in select()
n = fd2 + 1;
/* bind the socket to any valid IP address and a specific port */
memset((char *)&myaddr, 0, sizeof(myaddr));
myaddr.sin_family = AF_INET;
//myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
inet_pton(AF_INET, "192.168.10.10", &myaddr.sin_addr.s_addr);
myaddr.sin_port = htons(3000);
if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
perror("bind failed");
return 0;
}
///////////////////////////
memset((char *)&myaddr2, 0, sizeof(myaddr2));
myaddr2.sin_family = AF_INET;
//myaddr2.sin_addr.s_addr = htonl(INADDR_ANY);
inet_pton(AF_INET, "192.168.11.11", &myaddr2.sin_addr.s_addr);
myaddr2.sin_port = htons(4000);
if (bind(fd2, (struct sockaddr *)&myaddr2, sizeof(myaddr2)) < 0) {
perror("bind2 failed");
return 0;
}
// wait until either socket has data ready to be recv()d (timeout 10.5 secs)
tv.tv_sec = 50;
tv.tv_usec = 500000;
for (;;) {
int rv = select(n, &readfds, NULL, NULL, &tv);
if (rv == -1) {
perror("select"); // error occurred in select()
} else if (rv == 0) {
printf("Timeout occurred! No data after 10.5 seconds.\n");
} else {
// one or both of the descriptors have data
if (FD_ISSET(fd, &readfds)) {
printf("socket %i RECEIVED A PACKET \n", fd);
printf("waiting on port %d\n", myaddr.sin_port);
recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
if (recvlen > 0) {
buf[recvlen] = 0;
printf("received message: \"%s\" (%d bytes)\n", buf, recvlen);
}
else
printf("uh oh - something went wrong!\n");
//sprintf(buf, "ack %d", msgcnt++);
}
if (FD_ISSET(fd2, &readfds)) {
printf("socket %i RECEIVED A PACKET \n", fd2);
printf("waiting on port %d\n", myaddr2.sin_port);
recvlen2 = recvfrom(fd2, buf2, BUFSIZE, 0, (struct sockaddr *)&remaddr2, &addrlen2);
if (recvlen2 > 0) {
buf[recvlen2] = 0;
printf("received message2: \"%s\" (%d bytes)\n", buf2, recvlen2);
}
else
printf("uh oh - something went wrong2!\n");
//sprintf(buf, "ack %d", msgcnt++);
}
}
}
}
result is shown in the picture:
================
Right now i checked the program in ns3 simulator network. It works correctly. so it seems that problem is with loopback. Please guide me how could i make loopback and test it over localhost.
Related
I'm having issues with my connect() method on the client side of my socket programming. I'm not sure if the issue is with my code or my method of running it. I'm running it in two seperate terminal windows - one for the server (which I'm running first) with the command './server 8080' and one for the client with the command './client 4 8080 hello'. When I run my code, the server program stops in the while loop just after the printf("this prints\n") line. I presume this means that it is waiting for a client to connect to it. The client program fails on the connect() call, and prints out my error message "Connection Failed". My code is posted below.
Server Code:
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <sys/wait.h>
#define bufsize 1024
void eatZombies(int n){
wait3(NULL,WNOHANG,NULL); // Nom Nom
}
int main(int argc, char *argv[]){
int sock, length, msgsock, status;
struct sockaddr_in server;
pid_t id;
signal(SIGCHLD, &eatZombies);
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(atoi(argv[1])); // this time 1st arg is port#
if(bind(server_fd, (struct sockaddr *)&server, sizeof(server)) < 0){
printf("Error binding the socket\n");
exit(0);
}
if(listen(server_fd, SOMAXCONN) < 0){
printf("Error listening for connections\n");
exit(0);
}
char buffer[1024] = {0};
char *hello = "Hello from server";
int addrlen = sizeof(server);
while(1){
printf("this prints\n");
int client_fd = accept(server_fd, (struct sockaddr *)&server, (socklen_t*)&addrlen);
printf("this doesnt\n");
if(client_fd < 0){
printf("Error accepting connection\n");
exit(0);
}
// the next call makes a new child process that will actually handle the client.
id = fork();
// when id == 0, this is the child and needs to do the work for the server.
// when if > 0, this is the parent, and it should just loop around,
// when id < 0, we had an error.
if(id > 0){
continue;
}
else if(id < 0){
printf("Error\n");
exit(0);
}
read(client_fd, buffer, 1024);
printf("%s\n", buffer);
write(client_fd, hello, strlen(hello), 0);
printf("Hello message sent\n");
exit(0);
}
return 0;
}
Client Code:
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define bufsize 1024
int main(argc, argv) int argc; char *argv[];{
int sock, rval;
struct hostent *host;
struct sockaddr_in server; // not a pointer
char buf[bufsize];
printf("%d\n", argc);
if(argc != 4){
printf("usage:\ntcpclient hostname port string\n\n");
return(-1);
}
// look up hostname (server) using DNS
if ((host = gethostbyname(argv[1])) == 0) {
fprintf(stderr, "%s: unknown host\n", argv[1]);
return(-1);
}
// Set up fields for socket to point to host and port
bcopy(host->h_addr, &server.sin_addr, host->h_length);
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[2]));
// Create socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0){
printf("Socket Creation Failed\n");
exit(0);
}
// connect (3-way handshake)
if(connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0){
printf("Connection Failed\n");
exit(0);
}
// Copy the arg into buf so we can send it to the server
strncpy(buf, argv[3], bufsize);
// Send sentence to server
send(sock, buf, strlen(buf), 0);
printf("Message sent\n");
// read response from server
rval = read(sock, buf, bufsize);
// print result to window
fprintf(stdout,"%s\n", buf);
close(sock);
}
When running ./client 4 8080 hello, 4 is the host name. You meant to call ./client localhost 8080 hello.
So it was just a mistake in calling the application, not in the code.
I am using this code to receive data from a sensor through sockets. The problem is that I keep receiving the same output for every iteration of the for loop. However I receive a different number for every time I run the code but again, the same number keeps repeating. The sensor should send different every time data but thats not the case here.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "port.h"
#define BUFSIZE 2048
int
main(int argc, char **argv)
{
struct sockaddr_in myaddr; /* our address */
struct sockaddr_in remaddr; /* remote address */
socklen_t addrlen = sizeof(remaddr); /* length of addresses */
int recvlen; /* # bytes received */
int fd; /* our socket */
int msgcnt = 0; /* count # of messages we received */
unsigned char buf[BUFSIZE]; /* receive buffer */
/* create a UDP socket */
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("cannot create socket\n");
return 0;
}
/* bind the socket to any valid IP address and a specific port */
memset((char *)&myaddr, 0, sizeof(myaddr));
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
myaddr.sin_port = htons(SERVICE_PORT);
if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
perror("bind failed");
return 0;
}
/* now loop, receiving data and printing what we received */
printf("waiting on port %d\n", SERVICE_PORT);
printf("%s \n \n", "We recieve 10 packets just to confirm the communication");
recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
if (recvlen > 0) {
buf[recvlen] = 0;
printf("received message: \"%u\" (%d bytes)\n", buf, recvlen);
}
else
printf("uh oh - something went wrong!\n");
sprintf(buf, "ack %d", msgcnt++);
printf("sending response \"%u\"\n", buf);
if (sendto(fd, buf, strlen(buf), 0, (struct sockaddr *)&remaddr, addrlen) < 0)
perror("sendto");
int temp = recvlen;
for (;;) {
recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
if (recvlen > 0) {
buf[recvlen] = 0;
printf("received message: \"%u\" (%d bytes)\n", buf, recvlen);
}
}
}
Edit:
Here is the output when i ran the code two seperate times:
trial run and
trial run 2
I believe the problem isn't with your networking code but rather with your printf() calls:
printf("received message: \"%u\" (%d bytes)\n", buf, recvlen);
You are specifying %u to print out the contents of buf, but buf is a char array (not an unsigned integer), so you probably want to be using %s instead.
I am trying to get a very basic hello world UDP sender and UDP multicast listener to work. I have a PC but have a virtual machine with the Linux OS CentOS. It has no problems connecting to the internet. The sender and listener are two separate programs, Eclipse is my environment.
The Sender...
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#define UDP_PORT 5403
#define UDP_GROUP "225.0.0.1" // 127.0.0.1
int main(int argc, char *argv[])
{
struct sockaddr_in addr;
int fd;
struct ip_mreq mreq;
char *message="Hello, World!";
int message_size = strlen(message) + 1;
// Create a UDP socket
fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0)
{
perror("socket(...) ");
return -1;
}
// allow multiple sockets to use the same PORT number
u_int reuse_port = 1;
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &reuse_port, sizeof(reuse_port)) < 0)
{
perror("setsockopt(...) ");
return -1;
}
// set up destination address
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(UDP_GROUP);
addr.sin_port = htons(UDP_PORT);
printf("Begin sendto(...) infinite loop\n");
while (true)
{
printf("Sending message: %s, of size: %d\n", message, message_size);
if (sendto(fd, message, message_size, 0, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
perror("sendto(...): ");
return -1;
}
// printf("message sent: %s\n", message);
sleep(1);
}
return 1;
}
The Listener...
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#define UDP_PORT 5403
#define UDP_GROUP "225.0.0.1"
#define MAX_BUFFER_SIZE 256
int main(int argc, char *argv[])
{
struct sockaddr_in addr;
int fd, nbytes;
socklen_t addrlen;
struct ip_mreq mreq;
char msgbuf[MAX_BUFFER_SIZE];
u_int reuse_port = 1;
// Create a socket
fd = socket(AF_INET,SOCK_DGRAM,0);
if (fd < 0)
{
perror("create socket failed");
return -1;
}
// allow multiple sockets to use the same PORT number
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_port, sizeof(reuse_port)) < 0)
{
perror("Reusing port number failed");
return -1;
}
// set up destination address
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(UDP_PORT);
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
perror("bind");
return -1;
}
// Set the recvfrom timeout after 1 s
struct timeval tv;
tv.tv_sec = 2;
tv.tv_usec = 0;
if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0)
{
perror("Error setting recvfrom timeout\n");
return -1;
}
// use setsockopt() to request that the kernel join a multicast group
mreq.imr_multiaddr.s_addr = inet_addr(UDP_GROUP);
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
{
perror("setsockopt");
return -1;
}
addrlen = sizeof(addr);
printf("Begin recvfrom(...) infinite loop\n");
while (true)
{
nbytes = recvfrom(fd, msgbuf, MAX_BUFFER_SIZE, 0, (struct sockaddr *)&addr, &addrlen);
if (nbytes < 0)
{
printf("recvfrom timeout\n");
}
else
{
printf("message received: %s\n", msgbuf);
}
}
return 1;
}
Every second, the sender program printf's "Sending message: Hello, World!, of size: 14" and every two seconds the receiver printf's "recvfrom timeout". I have set Wireshark to look at UDP traffic and I definitely see the sento data. The recvfrom is not getting any data. I have tried using many different Group IP's from 255.0.0.0 to 239.255.255.255, no change. I have tried many different ports, no change. Is their a special setup I need to do on my network card? I'm not sure what else to do. Small edit, the recvfrom and sendto message should not have "&".
Following is a single server-client code which are trying to send-receive few buffers, and later close the connection.
Server Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <arpa/telnet.h>
#include <unistd.h>
char buff1[][3]= {{0xff , 0xfd, 0x18},{0xff , 0xfd, 0x1e},{0xff , 0xfd, 0x1d}};
char recbuf[1024];
void mwrite (int sock, char * buf, int size)
{
int n = send( sock, buf, size, 0 );
if (n < 0)
{
perror("ERROR writing to socket");
return;
}
}
void read (int sock)
{
char buffer[256];
/* Now read client response */
memset(buffer, 0, sizeof(buffer));
int n = recv( sock, buffer, 255, 0 );
if (n < 0)
{
perror("ERROR reading from socket");
return;
}
for (int i = 0; i < n; i++)
printf("%2x ", buffer[i]);//printing ascii characters
printf("\n");
}
int main(int argc , char *argv[] )
{
int sockfd , newsockfd , portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
sockfd = socket(AF_INET , SOCK_STREAM , 0);
if (sockfd < 0 )
{
perror("Error opening socket ");
exit(1);
}
/* Initialize socket structure */
bzero((char *) &serv_addr , sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY ;
serv_addr.sin_port = htons(portno);
/* Now bind the host address using client */
if(bind(sockfd, (struct sockaddr *) &serv_addr , sizeof(serv_addr)) <0)
{
perror("Error on binding");
exit(1);
}
if(listen(sockfd,5)<0)
{
perror("Error on listen");
exit(1);
}
int count = 1;
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
{
perror("ERROR on accept");
exit(1);
}
printf("Server Sending (DO TERMINAL TYPE)\n");
while ((n = write(newsockfd,buff1,sizeof(buff1)))>0)
{
printf("Server Sent query %d: %x %x %x\n", count, buff1[count][0], buff1[count][1], buff1[count][2]);
n = read(newsockfd, recbuf , sizeof(recbuf));
printf("Server received responset: %x %x %x\n", recbuf[0], recbuf[1], recbuf[2]);
count++;
count = count % 3;
if(n<0)
{
perror("Error writing to socket ");
exit(1);
}
}
return 0 ;
}
Client Code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <arpa/telnet.h>
#include <unistd.h>
#include <netdb.h>
char buff2[] = {0xff,0xfc,0x18};
void read (int sock)
{
char buffer[256];
/* Now read server response */
memset(buffer, 0, sizeof(buffer));
int n = recv( sock, buffer, 255, 0 );
if (n < 0)
{
perror("ERROR reading from socket");
return;
}
printf("\n%d bytes received buffer is: %s", n, buffer);
}
void mwrite (int sock, char * buf, int size)
{
int n = send( sock, buf, size, 0 );
if (n < 0)
{
perror("ERROR writing to socket");
return;
}
printf("Bytes Sent: %d\n", n);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server1;
char buffer1[256];
if (argc < 3)
{
fprintf(stderr,"usage %s hostname port\n", argv[0]);
return(0);
}
portno = atoi(argv[2]);
/* Create a socket point */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("ERROR opening socket");
return(1);
}
server1 = gethostbyname(argv[1]);
if (server1 == NULL)
{
fprintf(stderr,"ERROR no such host \n");
exit(0);
}
bzero((char *) &serv_addr , sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server1->h_addr, (char*)&serv_addr.sin_addr.s_addr, server1->h_length);
serv_addr.sin_port = htons( portno );
/*Connect to server*/
if (connect( sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr) ) < 0)
{
perror("ERROR connecting");
return(1);
}
printf("Recieving Buffer 1 from Server side");
bzero(buffer1,256);
while(true)
{
n= read(sockfd,buffer1,sizeof(buffer1));
if(n<0)
printf("ERROR reading in socket %d len %d", n, sizeof(buffer1));
n= write(sockfd,buff2,sizeof(buff2));
if(n<0)
printf("ERROR writing in socket %d len %d", n, sizeof(buff2));
printf("\nSent Buffer2 (WON'T TERMINAL TYPE) from client side");
}
return 0;
}
Output :
Server Side :
./single_sample 5667
Server Sending (DO TERMINAL TYPE)
Server Sent query 1: ffffffff fffffffd 1e
Server received responset: ffffffff fffffffc 18
Server Sent query 2: ffffffff fffffffd 1d
Server received responset: ffffffff fffffffc 18
Error writing to socket : Connection reset by peer
Client Side:
./sample_client 127.0.0.1 5667
Recieving Buffer 1 from Server side
Sent Buffer2 (WON'T TERMINAL TYPE) from client side
Basically I am trying to close the socket once both the buffers are sent. But getting the above error. I am unable to solve whether the error is occuring from server side or client side.
Also, while running this code on a linux machine how to capture the data bytes sent on wireshark
Thanks in advance.
Your client writes its message and then immediately disconnects, which leads the server to get the Connection reset by peer error - since the client part of the connection no longer exists.
First of all, I'd like to point out that i'm not a good programmer, so please be patient with me. The logic in the program is as follows: the client sends the server a text file, the server saves it under a different name. In short, very similar to this topic:
" File transfer server/client using socket " except that I'm using a different protocol. I think I've managed to succesfully send the file, but it seems like the server, afters creating a blank file, stucks in a loop/doesn't write anything in it.
Here's the code for the client:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h> /* memset() */
#include <sys/time.h> /* select() */
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#define REMOTE_SERVER_PORT 1500
#define MAX_MSG 100
#define PLIK "/home/aatami/Documents/programowanie/serwer/plik.txt"
#define LENGTH 512
int main(int argc, char *argv[]) {
int sd, rc, i,fd;
unsigned int cliLen;
struct sockaddr_in cliAddr, remoteServAddr;
struct hostent *h;
char buf[LENGTH];
/* check command line args */
if(argc<3) {
printf("usage : %s <server> <data1> ... <dataN> \n", argv[0]);
exit(1);
}
/* get server IP address (no check if input is IP address or DNS name */
h = gethostbyname(argv[1]);
if(h==NULL) {
printf("%s: unknown host '%s' \n", argv[0], argv[1]);
exit(1);
}
printf("%s: sending data to '%s' (IP : %s) \n", argv[0], h->h_name,
inet_ntoa(*(struct in_addr *)h->h_addr_list[0]));
remoteServAddr.sin_family = h->h_addrtype;
memcpy((char *) &remoteServAddr.sin_addr.s_addr,
h->h_addr_list[0], h->h_length);
remoteServAddr.sin_port = htons(REMOTE_SERVER_PORT);
/* socket creation */
sd = socket(AF_INET,SOCK_DGRAM,0); /* port 0 - system gets the first free one */
if(sd<0) {
printf("%s: cannot open socket \n",argv[0]);
exit(1);
}
/* bind any port */
cliAddr.sin_family = AF_INET;
cliAddr.sin_addr.s_addr = htonl(INADDR_ANY);
cliAddr.sin_port = htons(0);
rc = bind(sd, (struct sockaddr *) &cliAddr, sizeof(cliAddr));
if(rc<0) {
printf("%s: cannot bind port\n", argv[0]);
exit(1);
}
/* send data */
for(i=2;i<argc;i++) {
rc = sendto(sd, argv[i], strlen(argv[i])+1, 0,
(struct sockaddr *) &remoteServAddr,
sizeof(remoteServAddr));
if(rc<0) {
printf("%s: cannot send data %d \n",argv[0],i-1);
close(sd);
exit(1);
}
/* send text file */
char sdbuf[LENGTH];
printf("[Client] Sending %s to the Server... ", PLIK);
FILE *fs = fopen(PLIK, "r");
if(fs == NULL)
{
printf("ERROR: File %s not found.\n", PLIK);
exit(1);
}
bzero(sdbuf, LENGTH);
int fs_block_sz;
while((fs_block_sz = fread(sdbuf, sizeof(char), LENGTH, fs)) > 0)
{
if(send(sd, sdbuf, fs_block_sz, 0) < 0)
{
fprintf(stderr, "ERROR: Failed to send file %s. (errno = %d)\n", PLIK, errno);
break;
}
bzero(sdbuf, LENGTH);
}
printf("Ok File %s from Client was Sent!\n", PLIK);
}
return 1;
}
And the code for the server:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> /* close() */
#include <string.h> /* memset() */
#include <errno.h>
#define LENGTH 512
#define LOCAL_SERVER_PORT 1500
#define MAX_MSG 100
#define PLIKSERV "/home/aatami/Documents/programowanie/serwer/plikserv.txt"
int main(int argc, char *argv[]) { /* licznik argumentow, tablica argumentow */
int sd, rc,nsockfd;
unsigned int n,cliLen;
struct sockaddr_in cliAddr, servAddr;
char msg[MAX_MSG];
char buf[512],sbuf[LENGTH];
/* socket creation */
sd=socket(AF_INET, SOCK_DGRAM, 0);
if(sd<0) {
printf("%s: cannot open socket \n",argv[0]);
exit(1);
}
/* bind local server port */
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(LOCAL_SERVER_PORT);
rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr));
if(rc<0) {
printf("%s: cannot bind port number %d \n",
argv[0], LOCAL_SERVER_PORT);
exit(1);
}
printf("%s: waiting for data on port UDP %u\n",
argv[0],LOCAL_SERVER_PORT);
/* server infinite loop */
while(1) {
/* init buffer */
memset(msg,0x0,MAX_MSG);
/* receive message */
cliLen = sizeof(cliAddr);
n = recvfrom(sd, msg, MAX_MSG, 0,
(struct sockaddr *) &cliAddr, &cliLen);
if(n<0) {
printf("%s: cannot receive data \n",argv[0]);
continue;
}
/* print received message */
printf("%s: from %s:UDP%u : %s \n",
argv[0],inet_ntoa(cliAddr.sin_addr),
ntohs(cliAddr.sin_port),msg);
unsigned int sin_size = sizeof(struct sockaddr_in);
FILE *fr = fopen(PLIKSERV, "a");
if(fr == NULL)
printf("File %s Cannot be opened file on server.\n", PLIKSERV);
else
{
bzero(sbuf, LENGTH);
int fr_block_sz = 0;
while((fr_block_sz = recvfrom(sd, buf, LENGTH, 0,(struct sockaddr *) &cliAddr, &cliLen)) > 0)
{
int write_sz = fwrite(buf, sizeof(char), fr_block_sz, fr);
if(write_sz < fr_block_sz)
{
perror("File write failed on server.\n");
}
bzero(buf, LENGTH);
if (fr_block_sz == 0 || fr_block_sz != 512)
{
break;
}
}
if(fr_block_sz < 0)
{
if (errno == EAGAIN)
{
printf("recv() timed out.\n");
}
else
{
fprintf(stderr, "recv() failed due to errno = %d\n", errno);
exit(1);
}
}
printf("Ok received from client!\n");
fclose(fr);
}
}/* end of server infinite loop */
return 0;
}
Any help greatly appreciated!
After seen your code I'd suggest try to send a "Hello world\n" from client to the server, see if you get it there. Once you make the connection between client and server then try to expand the code to do a file transfer.
But keep this in mind about UDP:
"UDP uses a simple transmission model with a minimum of protocol mechanism. It has no handshaking dialogues, and thus exposes any unreliability of the underlying network protocol to the user's program. As this is normally IP over unreliable media, there is no guarantee of delivery, ordering or duplicate protection. If error correction facilities are needed at the network interface level, an application may use the Transmission Control Protocol (TCP) which is designed for this purpose."
As you start the client, it sends all packets as fast as possible, could it be that the packets get lost or disordered or even duplicates at the server site. I also suggest waiting for a packet to acknowledge the correct reception. I mean, when then server receives a packet it sends a packet to acknowledge it to the client. This way, a conversation (dialog) could be held and the transfer accomplished satisfactory.