socket fdopen问题

caoshufengcao 2012-10-16 08:13:26

#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/socket.h>
#include <string.h>
#include <fcntl.h>

int main(void) {
struct sockaddr_in sin;
struct sockaddr_in cin;
int lfd;
int afd;
FILE * fp;
socklen_t len;
char buf[400];
bzero(&sin,sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(8000);
sin.sin_addr.s_addr = INADDR_ANY;
lfd = socket(AF_INET,SOCK_STREAM,0);
if(lfd < 0) {
perror("socket");
exit(1);
}
if(bind(lfd,(struct sockaddr *)&sin,sizeof(sin)) == -1) {
perror("bind");
exit(1);
}
listen(lfd,10);
while(1) {
bzero(buf,400);
afd = accept(lfd,(struct sockaddr *)&cin,&len);
if(afd < 0) {
perror("afd");
exit(1);
}
printf("错在哪?\n");
fp = fdopen(afd,"a+");
fgets(buf,400,fp);
printf("%s\n",buf);
fclose(fp);
close(afd);
}
return EXIT_SUCCESS;
}



每次加上

fp = fdopen(afd,"a+");
fgets(buf,400,fp);
printf("%s\n",buf);

这几行,我设置断点,居然在:
afd = accept(lfd,(struct sockaddr *)&cin,&len);这一行出错:
运行结果:
afd: Invalid argument

如果不加这几行,就不报错?为什么?求解
...全文
251 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
AzureWood 2012-10-17
  • 打赏
  • 举报
回复
你自己代码写的很清楚了啊,
fopen(***,"a+");这是追加方式,默认文件指针是到文件尾部的,因此你一gets就会出错
fopen(***,"r");这是读方式,默认开始指针是在文件头部的,因此你gets没问题
Geoff08Zhang 2012-10-16
  • 打赏
  • 举报
回复
在accept前增加len = sizeof(cin);
armsword 2012-10-16
  • 打赏
  • 举报
回复
int lfd;
int afd;

把他们声明为SOCKET类型,因为accept返回SOCKET类型。。

之后
if(lfd < 0) {
perror("socket");
exit(1);
}

之力用是否 == SOCKET_ERROR 判断。
caoshufengcao 2012-10-16
  • 打赏
  • 举报
回复
不是的,以下是一断可以用的代码,但这是什么原因?

#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/socket.h>
#include <string.h>
#include <fcntl.h>

int main(void) {
struct sockaddr_in sin;
struct sockaddr_in cin;
int lfd;
int afd;
FILE * fp;
FILE * fp1;
socklen_t len;
char buf[400];
bzero(&sin,sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(8000);
sin.sin_addr.s_addr = INADDR_ANY;
lfd = socket(AF_INET,SOCK_STREAM,0);
if(lfd < 0) {
perror("socket");
exit(1);
}
if(bind(lfd,(struct sockaddr *)&sin,sizeof(sin)) == -1) {
perror("bind");
exit(1);
}
listen(lfd,10);
while(1) {
bzero(buf,400);
afd = accept(lfd,(struct sockaddr *)&cin,&len);
if(afd < 0) {
perror("afd");
exit(1);
}
fp = fdopen(afd,"r");
fp1 = fdopen(afd,"w");
while(fgets(buf,400,fp)) {
if(strlen(buf) == 2)
break;
if(strstr(buf,"POST")) {
printf("post提交。\n");
}
printf("%s",buf);
}
fputs("HTTP/1.1 200\r\n",fp1);
fflush(fp1);
fclose(fp1);
fclose(fp);
close(afd);
}
return EXIT_SUCCESS;
}
wliangde 2012-10-16
  • 打赏
  • 举报
回复
你的len没有初始化吧。
加上 len = sizeof(cin);
caoshufengcao 2012-10-16
  • 打赏
  • 举报
回复

fp = fdopen(afd,"r");
fp1 = fdopen(afd,"w");
fgets(buf,400,fp);
printf("%s\n",buf);
fclose(fp);
close(afd);

刚刚翻了下unix网络编程,上面也值点了一下,才十行代码,借鉴了下,居然没出错,可这是为什么啊?

70,037

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧