Linux 中的 socket 编程:C和C++有什么不同?

0rookie0 2003-09-29 04:05:13
我有一文件 a.c ,内容如下:
-------------------------------------------------------------------------
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char **argv)
{
struct sockaddr_in address;
int fd;
int address_len;
int rtval;
char hwChar = '0';

fd = socket(AF_INET, SOCK_STREAM, 0);
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = htons(1234);
address_len = sizeof(address);

rtval = connect(fd, (struct sockaddr *)&address, address_len);
if(rtval == -1) return 1;
write(fd, &hwChar, 1);
close(fd);
}
-------------------------------------------------------------------------

用命令 gcc -o a.o -c a.c 编译没任何错误。接着
cp a.c a.cxx
g++ -o axx.o a.cxx
报错信息如下:
a.cxx: In function `int main(int, char**)':
a.cxx:16: `inet_addr' undeclared (first use this function)
a.cxx:16: (Each undeclared identifier is reported only once for each function
it appears in.)
a.cxx:22: `write' undeclared (first use this function)
a.cxx:23: `close' undeclared (first use this function)

请问是什么原因?如果要在C++中进行 socket 编程,要怎么样做才行?
...全文
179 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xray2fly 2003-09-30
  • 打赏
  • 举报
回复
-lsocket 试试?
netsys2 2003-09-30
  • 打赏
  • 举报
回复
头文件改为:

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/uio.h>
#include <sys/socket.h>
#include <arpa/inet.h>


原因是C++和C的编译器默认包含的头文件不同



0rookie0 2003-09-30
  • 打赏
  • 举报
回复
netsys2 真是高人啊,完全正确!

非常感谢!
zihan 2003-09-29
  • 打赏
  • 举报
回复
应该和语言没有关系,在Windows下,只要包含winsock2.h就可以了,怀疑应该是头文件的问题,不知道linux是否可以找帮助了.看看在linux里面是不是叫这个东西.

4,354

社区成员

发帖
与我相关
我的任务
社区描述
通信技术相关讨论
社区管理员
  • 网络通信
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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