I am new to socket programming. I wrote codes for UDP Client and Server which work fine on my computer. I want to run these programs on two different hosts, i.e. the Server on my computer and Client on my friend' computer. How do I do it without a router? Please mention if any specific changes are to be made in the code for the purpose.
Here's the code:
Receiver
#include<stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<netinet/ip.h>
#include<string.h>
#include<unistd.h>
int main() {
int ret = socket(AF_INET, SOCK_DGRAM, 0);
if (ret == -1) {
printf("socket creation fails\n");
exit(0);
} else
printf("socket creation succeeds\n");
struct sockaddr_in sender;
int port;
printf("Enter port:");
scanf("%d", & port);
sender.sin_family = AF_INET;
sender.sin_port = htons(port);
sender.sin_addr.s_addr = INADDR_ANY;
int ret1;
ret1 = bind(ret, (struct sockaddr * ) & sender, sizeof(sender));
if (ret1 == -1) {
printf("socket binding fails\n");
exit(0);
}
printf("socket binding succeeds\n");
struct sockaddr_in receiver;
char str[15], str2[15];
int addrlen = sizeof(receiver);
while (1) {
int rec = recvfrom(ret, str, sizeof(str), 0, (struct sockaddr * ) & receiver, & addrlen);
printf("Received:");
str[rec] = '\0';
if (strcmp(str, "exit") == 0)
break;
if (rec == -1) {
printf("recvfrom fails\n");
exit(0);
}
printf("%s\n", str);
printf("Enter :");
scanf("%s", str2);
int recsend = sendto(ret, str2, strlen(str2), 0, (struct sockaddr * ) & receiver, sizeof(receiver));
if (recsend == -1) {
printf("sendto fails");
exit(0);
}
if (strcmp(str2, "exit") == 0)
break;
}
close(ret);
return 0;
}
Sender
#include<stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<netinet/ip.h>
#include<string.h>
#include<unistd.h>
int main() {
int ret = socket(AF_INET, SOCK_DGRAM, 0);
if (ret == -1) {
printf("\nsocket creation fails");
exit(0);
} else
printf("\nsocket creation succeeds");
struct sockaddr_in receiver;
int port;
printf("\nEnter port:");
scanf("%d", & port);
receiver.sin_family = AF_INET;
receiver.sin_port = htons(port);
receiver.sin_addr.s_addr = INADDR_ANY;
char str[15], str2[15];
int addrlen1 = sizeof(receiver);
struct sockaddr_in sender;
int addrlen = sizeof(sender);
while (1) {
printf("Enter:");
scanf("%s", str);
int send = sendto(ret, str, strlen(str), 0, (struct sockaddr * ) & receiver, addrlen1);
if (send == -1) {
printf("sendto fails");
exit(0);
}
if (strcmp(str, "exit") == 0)
break;
int senrec = recvfrom(ret, str2, sizeof(str2), 0, (struct sockaddr * ) & sender, & addrlen);
printf("\n");
printf("Received:");
str2[senrec] = '\0';
if (strcmp(str2, "exit") == 0)
break;
if (senrec == -1) {
printf("recvfrom fails\n");
exit(0);
}
printf("%s\n", str2);
}
close(ret);
return 0;
}