gpt4 book ai didi

C 套接字问题

转载 作者:行者123 更新时间:2023-11-30 19:10:29 25 4
gpt4 key购买 nike

我正在运行一个从命令行发送时区的客户端,以及一个测试服务器(我们知道它可以工作),返回该时区的日期和时间。但是,正确返回时区后,它会出现段错误。

下面是我的客户端代码:

int main(int argc, const char * argv[]){
char buf[kBufSize+1];
char line[128];
ssize_t n;
int i;
int more;
int x = 0;

int sockFD;
int port;
struct sockaddr_in sad;
struct hostent *ptrh;

sockFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
memset(&sad, 0, sizeof(sad)); /* Sets every byte of the address to be zero */
sad.sin_family = AF_INET;

/* Look up name */
ptrh = gethostbyname(argv[1]);
memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_length);

/* Set port */
//sscanf(argv[2], "%d", &port);
port = atoi(argv[2]);
//printf("%d",port);
sad.sin_port = htons(port);

int clifd = connect(sockFD, (struct sockaddr *)&sad, sizeof(sad));
if(clifd < 0) {
printf("[ERROR]: Error Connecting...\n");
return 0;
}
printf("Number of args: %d\n", argc);
x = 3;

//printf("Value of x: %d\n", x);
//printf("[DEBUG]: Value of X: %d\n", x);

//printf("[DEBUG]: Line: %s\n", line);
do
{
/* Read input line */
do
{
more = 1;
n = read(sockFD, buf, kBufSize);
buf[n] = '\0'; // BUF IS READ FROM THE SERVER

if(n <= 0)
break;

for(i = 0; i < n; i++)
{
if(buf[i] == 10)
{
more = 0;
break;
}
}

printf("%s", buf);

if (buf == "BYE\r\n"){
printf("Closing\n");
exit(1);
}

} while(more);

if(n <= 0)
{
break;
}
strcpy(line, argv[x]);
strcat(line, "\r\n\0"); // LINE IS SENT TO THE SERVER
//printf("[DEBUG] Being sent: %s", line);
write(sockFD, line, strlen(line));
//printf("%d", n);
//printf("Value of x: %d\n", x);
x++;
} while (n != 0 && x <= argc);

close(sockFD);
return 0;
}

最佳答案

argv 数组从 0 到 argc-1,但您使用的 argv 从 3 到 argc。查看外部 do/while 循环的条件。

关于C 套接字问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41169456/

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