UDP Server-Client

closed account (DGvMDjzh)
This is a simple server-client code. The client sends the first packet, server receives it along with the client's address and sends a response. The code works perfectly when SERVER_IP is set to "127.0.0.1", but every-time I try this over the internet the client never receives a response from the server.

What am I doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//Server
bool Server() {
 WSADATA WSA;
 SOCKET Socket;
 SOCKADDR_IN LocalAddr;

 if (WSAStartup(0x0202,&WSA)) return false;
 if (WSA.wVersion != 0x0202) return false;

 Socket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);

 LocalAddr.sin_family = AF_INET;
 LocalAddr.sin_port = htons(7777);
 LocalAddr.sin_addr.s_addr = INADDR_ANY;

 if (bind(Socket,(SOCKADDR*)&LocalAddr,sizeof(SOCKADDR))) return false;

 SOCKADDR_IN ClientAddr;
 int i = sizeof(SOCKADDR);
 char data[256];

// recieve first packet and get client address
 if (recvfrom(Socket,data,256,0,(SOCKADDR*)&ClientAddr,&i) <= 0) return false;

// send response
 if (sendto(Socket,data,256,0,(SOCKADDR*)&ClientAddr,sizeof(SOCKADDR_IN)) > 0) printf("Sent!");

 return true;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#define SERVER_IP "127.0.0.1"

//Client
bool Client() {
 WSADATA WSA;
 SOCKET Socket;
 SOCKADDR_IN ServerAddr;

 if (WSAStartup(0x0202,&WSA)) return false;
 if (WSA.wVersion != 0x0202) return false;

 Socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
 if (Socket == INVALID_SOCKET) return false;

 ServerAddr.sin_family = AF_INET;
 ServerAddr.sin_port = htons(7777);
 ServerAddr.sin_addr.s_addr = inet_addr(SERVER_IP);

 char data[256];

//send first packet
 if (sendto(Socket,data,256,0,(SOCKADDR*)&ServerAddr,sizeof(SOCKADDR_IN)) <= 0) return false;

//recieve response
 if (recvfrom(Socket,data,256,0,NULL,NULL) > 0) printf("Recieved!");

 return true;
}
but every-time I try this over the internet
What exactly does that mean? Where is the server program running?
closed account (DGvMDjzh)
Both the server and client are running on the same machine.
When the client sends the packet to the public IP address it does it successfully, but never receives a response from the server.
Last edited on
I don't know what this 'public IP address' is.


Usually the communication with the internet works (roughly) as follows:

Your computer sends a request to the modem. The modem sends this request to the server in the internet. And the response backwards.

In other words (usually): your computer doesn't have a public ip adress visible in the internet. Your modem (which is usually also a router) has.

closed account (DGvMDjzh)
Firewall issue, solved.
Last edited on
Topic archived. No new replies allowed.