I'm trying to create server and client through examples, I saw an example online and tried to make the same, but it didn't work for me and I don't understand why.
Server
int main(int argc, char *argv[])
{
int socket_fd, cc, fsize;
struct sockaddr_in s_in, from;
struct { char head; u_long body; char tail;} msg;
char name[10];
socket_fd = socket (AF_INET, SOCK_DGRAM, 0);
bzero((char *) &s_in, sizeof(s_in));
s_in.sin_family = (short)AF_INET;
s_in.sin_addr.s_addr = htonl(INADDR_ANY);
s_in.sin_port = htons((u_short)0x3333);
fflush(stdout);
bind(socket_fd, (struct sockaddr *)&s_in, sizeof(s_in));
for(;;) {
fsize = sizeof(from);
recvfrom(socket_fd,name,sizeof(name),0,(struct sockaddr *)&from,&fsize);
printf("Got data : %s",name);
fflush(stdout);
}
return 0;
}
Client
int main(int argc, char *argv[])
{
int socket_fd; //creating 1 int
struct sockaddr_in dest;
struct hostent *hostptr;
struct { char head; u_long body; char tail; } msgbuf;
char name[10];
socket_fd = socket (AF_INET, SOCK_DGRAM, 0);
bzero((char *) &dest, sizeof(dest));
hostptr = gethostbyname(argv[1]);
dest.sin_family = (short) AF_INET;
bcopy(hostptr->h_addr, (char *)&dest.sin_addr,hostptr->h_length);
dest.sin_port = htons((u_short)0x3333);
printf("Enter your name: ");
scanf("%s",name);
printf("%s",name);
sendto(socket_fd,name,sizeof(name),0,(struct sockaddr *)&dest,sizeof(dest));
return 0;
}
Can someone explain my problem?
NUL-terminate your buffer:
int n;
...
n = recvfrom(socket_fd,name,sizeof(name),0,(struct sockaddr *)&from,&fsize);
if (n == -1) {
perror("recvfrom");
exit(EXIT_FAILURE);
}
name[n] = '\0';
printf("Got data : %s",name);
...
Also note that bzero
and bcopy
are deprecated, use memset
and memmove
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.