What you are saying makes sense. Now my code looks like this:
Server
Code:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define N 100
#define M 50
#define K 100
int pars;
int main() {
int sock, n, nr;
socklen_t fromlen;
struct sockaddr_in server;
struct sockaddr_in from;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0)
printf("Can not create socket in server\n");
memset(&server, 0, sizeof(struct sockaddr_in));
server.sin_family = AF_INET;
server.sin_port = htons(5913);
server.sin_addr.s_addr = INADDR_ANY;
if(bind(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
printf("Can not bind in server!\n");
memset(&from, 0, sizeof(struct sockaddr_in));
fromlen = sizeof(struct sockaddr_in);
while(1) {
int n, l1;
fflush(stdout);
n = recvfrom(sock, &l1, sizeof(l1), 0, (struct sockaddr*) &from, &fromlen);
if (n < 0) {
printf("Can not receive in server!\n");
}
if (n == sizeof(nr)) printf("\n\nSuccess\n\n");
l1 = ntohl(l1);
printf("I have received %d from IP: %s, Port: %hu",l1,inet_ntoa(from.sin_addr), ntohs(from.sin_port));
}
}
Client
Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define N 100
int sock, n, nr, nr2;
socklen_t length;
struct sockaddr_in server, from;
void snd() {
int i,j;
length = sizeof(struct sockaddr_in);
nr = -1;
nr = htonl(nr);
n = sendto(sock, &nr, sizeof(nr), 0, (struct sockaddr *)&server, length);
if(n < 0) {
printf("Can not send from client");
}
nr = -2;
nr = htonl(nr);
n = sendto(sock, &nr, sizeof(nr), 0, (struct sockaddr *)&server, length);
if(n < 0) {
printf("Can not send from client");
}
}
void receive() {
}
int main() {
sock = socket(AF_INET, SOCK_DGRAM, 0);
if(sock < 0) {
printf("Can not create socket in client!\n");
}
srand(time(0));
memset(&server, 0, sizeof(struct sockaddr_in));
server.sin_family = AF_INET;
server.sin_port = htons(5913);
server.sin_addr.s_addr = inet_addr("127.0.0.1");
snd();
receive();
close(sock);
return 0;
}
The server prints "Success" each time he gets a number(the number received is the number sent).
I am using Ubuntu and compiling with gcc.
The port is still rubbish(range 50 000 - 60 000) and isn't consistent across different clients connecting to the same port.