问题描述
我C语言编写使用套接字的简单消息应用程序。当我使用功能 recvfrom的
,它返回 1
并设置错误号= 14
是错误地址
(这我在最后打印)。
但奇怪的是,它仍然从插座中读取并得到正确的消息。也就是说,应用程序可以正常使用,并如预期,除了这个错误。
我的问题是:为什么你觉得我得到这个错误?我想不出任何理由。我使用 inet_pton
设置同行方式> sin_addr
,但我得到了同样的错误。
//套接字文件描述符通过发送数据
INT recv_sock_fd =插座(PF_INET,SOCK_DGRAM,IPPROTO_UDP);//填写在同行的地址,环回在这种情况下,
结构SOCKADDR_IN *同行=的malloc(sizeof的(结构SOCKADDR_IN));
同行> sin_family = AF_INET;
同行> sin_port = htons(11110);
字符*新的=及(同行> sin_addr);
新的[0] = 127;
新的[1] = 0;
新[2] = 0;
新[3] = 1;
的for(int i = 0; I< 8;我++){
同行>的sin_zero [我] = NULL;
}绑定(recv_sock_fd,同行,的sizeof(结构SOCKADDR_IN));//检查是否插座有数据... code删除字符的buff [32] = {0};
错误号= 0;
INT bytes_received = recvfrom的(recv_sock_fd,浅黄色,sizeof的(BUFF),NULL,(结构sockaddr *)同行,的sizeof(结构SOCKADDR_IN));的printf(字节收到数:%d:%d个:%S \\ n,bytes_received,错误号,字符串错误(错误));
看的:
ssize_t供recvfrom的(INT的sockfd,无效* buf中,为size_t的len,诠释旗帜,
结构sockaddr * SRC_ADDR中,socklen_t * addrlen中);
最后一个参数是一个的地址的,当你给它一个简单的整数。
然后你正在构建的IP地址是错误的。不要使用,这就是它是。同时检查 绑定(2)
,它现在肯定失败。
I am writing a simple messaging application in C using sockets. When I use function recvfrom
, it returns -1
and sets errno = 14
which is Bad address
(which I am printing at the end).
The strange thing is that it still reads from the socket and gets the correct message. That is, the application is working perfectly and as expected except for that error.
My question is this: Why do you think I am getting this error? I cannot think of any reason. I was using inet_pton
to set peer->sin_addr
but I was getting the same error.
// socket file descriptor to send data through
int recv_sock_fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
// fill in the peer's address, loopback in this case
struct sockaddr_in *peer = malloc(sizeof(struct sockaddr_in));
peer->sin_family = AF_INET;
peer->sin_port = htons(11110);
char *new = &(peer->sin_addr);
new[0] = 127;
new[1] = 0;
new[2] = 0;
new[3] = 1;
for (int i = 0; i < 8; i++) {
peer->sin_zero[i] = NULL;
}
bind(recv_sock_fd, peer, sizeof(struct sockaddr_in));
// check to see if the socket has any data...code removed
char buff[32] = {0};
errno = 0;
int bytes_received = recvfrom(recv_sock_fd, buff, sizeof(buff), NULL, (struct sockaddr *)peer, sizeof(struct sockaddr_in));
printf("Bytes recieved: %d: %d : %s\n", bytes_received, errno, strerror(errno));
Look at the signature of recvfrom(2)
:
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen);
Last argument is an address, while you are giving it a plain integer.
Then you're building of the IP address is wrong. Do use inet_pton(3)
, that's what it's for. Also check the return value of the bind(2)
, it's surely failing now.
这篇关于简单邮件应用程序......让错误号14:错误的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!