udp client/server

closed account (oizT0pDG)
this is my udp client code....

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
30
31
32
33
34
35
36
37
38
#include<iostream>
#include<arpa/inet.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;

void error( char *msg)
{
 perror(msg);
 exit(EXIT_FAILURE);
}
int main()
{
 int sockfd;
 sockfd = socket(AF_INET,SOCK_DGRAM,0);
 struct sockaddr_in serv,client;
 
 serv.sin_family = AF_INET;
 serv.sin_port = htons(53000);
 serv.sin_addr.s_addr = inet_addr("127.0.0.1");

 char buffer[256];
 socklen_t l = sizeof(client);
 socklen_t m = sizeof(serv);
 //socklen_t m = client;
 cout<<"\ngoing to send\n";
 cout<<"\npls enter the mssg to be sent\n";
 fgets(buffer,256,stdin);
 sendto(sockfd,buffer,sizeof(buffer),0,(struct sockaddr *)&serv,m);
 recvfrom(sockfd,buffer,256,0,(struct sockaddr *)&client,&l);
}




this is my udp server code....

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<iostream>
#include<arpa/inet.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;

void error( char *msg)
{
 perror(msg);
 exit(EXIT_FAILURE);
}
int main()
{
 int sockfd;
 sockfd = socket(AF_INET,SOCK_DGRAM,0);
 struct sockaddr_in serv,client;
 
 serv.sin_family = AF_INET;
 serv.sin_port = htons(53000);
 serv.sin_addr.s_addr = inet_addr("127.0.0.1");

 char buffer[256];
 socklen_t l = sizeof(client);
 //socklen_t m = client;
 cout<<"\ngoing to recv\n";
 int rc= recvfrom(sockfd,buffer,sizeof(buffer),0,(struct sockaddr *)&client,&l);
 if(rc<0)
 {
 cout<<"ERROR READING FROM SOCKET";
 }
 cout<<"\n the message received is : "<<buffer<<endl;
 int rp= sendto(sockfd,"hi",2,0,(struct sockaddr *)&client,l);
 
 if(rp<0)
 {
 cout<<"ERROR writing to SOCKET";
 }
}



this is the first time i am doing socket programming...this is compiling and running but there is no comunication between the socket and client..
The real problem is that the server isn't binding to an address. As a result, the client can't connect to it.

To bind, you should construct a struct sockaddr_in that has address INADDR_ANY (to bind to all IP4 network interfaces), then use that address with bind().

You're not specifying the network protocol when you create the socket. You may or may not get away with it. The actual value in this case should be IPPROTO_UDP, not zero.

Also, you should close the socket at the end.
Topic archived. No new replies allowed.