我想对c++和套接字进行一些修改,所以我复制了一个示例服务器/客户端来对其进行测试。我已经编译好了,但是服务器没有收到任何消息。
客户端:
/* UDP client in the internet domain */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
void error(const char *);
int main(int argc, char *argv[])
{
int sock, n;
unsigned int length;
struct sockaddr_in server, from;
struct hostent *hp;
char buffer[256];
if (argc != 3) {
printf("Usage: server port\n");
exit(1);
}
sock= socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) error("socket");
server.sin_family = AF_INET;
hp = gethostbyname(argv[1]);
if (hp==0) error("Unknown host");
/*bcopy((char *)hp->h_addr,
(char *)&server.sin_addr,
hp->h_length);*/
memcpy((char *)hp->h_addr,
(char *)&server.sin_addr,
hp->h_length);
server.sin_port = htons(atoi(argv[2]));
length=sizeof(struct sockaddr_in);
printf("Please enter the message: ");
//bzero(buffer,256);
memset(buffer, 0, 256);
fgets(buffer,255,stdin);
n=sendto(sock,buffer,
strlen(buffer),0,(const struct sockaddr *)&server,length);
if (n < 0) error("Sendto");
n = recvfrom(sock,buffer,256,0,(struct sockaddr *)&from, &length);
if (n < 0) error("recvfrom");
write(1,"Got an ack: ",12);
write(1,buffer,n);
close(sock);
return 0;
}
void error(const char *msg)
{
perror(msg);
exit(0);
}
服务器:
/* Creates a datagram server. The port
number is passed as an argument. This
server runs forever */
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <netdb.h>
#include <stdio.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sock, length, n;
socklen_t fromlen;
struct sockaddr_in server;
struct sockaddr_in from;
char buf[1024];
if (argc < 2) {
fprintf(stderr, "ERROR, no port provided\n");
exit(0);
}
sock=socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) error("Opening socket");
length = sizeof(server);
//bzero(&server,length);
memset(&server, 0, length);
server.sin_family=AF_INET;
server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=htons(atoi(argv[1]));
if (bind(sock,(struct sockaddr *)&server,length)<0)
error("binding");
fromlen = sizeof(struct sockaddr_in);
while (1) {
n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from,&fromlen);
if (n < 0) error("recvfrom");
write(1,"Received a datagram: ",21);
write(1,buf,n);
n = sendto(sock,"Got your message\n",17,
0,(struct sockaddr *)&from,fromlen);
if (n < 0) error("sendto");
}
return 0;
}
作为端口,我使用1337,作为cleint的IP,我尝试使用127.0.0.1和localhost。在我写完一条消息后,两个程序在15分钟内都没有执行任何操作,然后关闭了终端。
我用过google,但是什么也没找到(但是我不确定我应该搜索什么)。
最佳答案
在客户端中,您正在将&server.sin_addr
复制到hp->h_addr
,但是您应该采用其他方法。
(与memcpy
相比,bcopy
以相反的顺序获取其源和目标参数。)
这意味着您正在使用未初始化的地址,并将数据包发送到某个随机位置。
它应该是
memcpy((char *) &server.sin_addr,
(char *) hp->h_addr,
hp->h_length);
关于c++ - Ubuntu C++ UDP包未到达,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37547391/