gpt4 book ai didi

c - 打开套接字时出错 : Success

转载 作者:太空宇宙 更新时间:2023-11-04 06:57:21 25 4
gpt4 key购买 nike

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>

void error(char *msg)
{
perror(msg);
exit(0);
}

int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;

char buffer[256];

if (argc < 3)
{
fprintf(stderr, "usage %s hostname port\n", argv[0]);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);

if (sockfd < 0);
{
error("ERROR opening socket");
}
server = gethostbyname(argv[1]);
if (server == NULL)
{
fprintf(stderr, "ERROR, no such host\n");
exit(0);
}
bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,(char *)&serv_addr.sin_addr.s_addr,server->h_length);

serv_addr.sin_port = htons(portno);
if(connect(sockfd, &serv_addr, sizeof(serv_addr)) < 0)
{
error("ERROR connecting");
}
printf("Please enter the message:");
bzero(buffer, 256);
fgets(buffer, 255, stdin);
n = write(sockfd, buffer, strlen(buffer));
if (n <0)
{
error("ERROR reading from socket");
}
printf("%s\n", buffer);
return 0;
}

当我运行这个程序时,我得到了错误

ERROR opening socket: Success

然后程序什么都不做。另外,我收到警告

 warning: passing argument 2 of ‘connect’ from incompatible pointer type [enabled by default]
if(connect(sockfd,&serv_addr, sizeof(serv_addr)) < 0)
^
In file included from Clientown.c:3:0:
/usr/include/sys/socket.h:138:12: note: expected ‘const struct sockaddr *’ but argument is of type ‘struct sockaddr_in *’
extern int connect (int __fd, __CONST_SOCKADDR_ARG __addr, socklen_t __len);

这是怎么回事?我是 c 的新手,我真的坚持使用这段代码。连接有问题吗?警告重要吗?有人可以帮我解决吗?谢谢。

最佳答案

你在不应该有分号的地方有一个分号:

if (sockfd < 0);
{
error("ERROR opening socket");
}

因此,error() 函数将始终被调用,即使 if 条件失败。你想要:

if (sockfd < 0)
{
error("ERROR opening socket");
}

关于c - 打开套接字时出错 : Success,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42617959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com