怎么用c编写socket程序?

cauiot 2002-09-29 01:20:31
请问一下,在c中能编写socket程序吗?

我曾经抄书抄了个程序:

//File Name :stream.c
#include <winsock.h>
#include <stdio.h>
#define DATA "half a league,half a league..."
//这个程序建立套接字,然后与命令行给出的套接字连接;连接结束时,在
//连接上发送一个消息,然后关闭套接字。命令行格式是:streamc 主机名 端口号。
//端口号要与服务器程序的端口号相同。
void main(int argc,char *argv[])
//int argc;
//char *argv[];
{
int sock;
struct sockaddr_in server;
struct hostent *hp,*gethostbyname();
char buf[1024];
//建立套接字。
sock=socket(AF_INET,SOCK_STREAM,0);
if(sock<0){
perror("opening stream socket");
exit(1);
}
//使用命令行中指定的名字连接套接字。
server.sin_family=AF_INET;
//hp=gethostbyname(argv[1]);
hp=gethostbyname();
if(hp==0){
fprintf(stderr,"%s: unknown host \n",argv[1]);
exit(2);
}
memcpy((char *)&server.sin_addr,(char *)hp->h_addr,hp->h_length);
server.sin_port=htons(atoi(argv[2]));
if(connect(sock,(struct sockaddr*)&server,sizeof(server))<0){
perror("connecting stream socket");
exit(3);
}
if(send(sock,DATA,sizeof(DATA),1)<0)
perror("sending on stream socket");
closesocket(sock);
exit(0);
}

但是在turboc2,turboc3中不能运行,在vc中也不能,我不知道是否vc的环境设置
不正确?(我查过,turboc中没有winsock.h头文件,但在vc中有的)
...全文
32 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
blh 2002-09-29
  • 打赏
  • 举报
回复
tc???搞笑嘛,呵呵
用vc也不行是你就没有打开socket,呵呵
必须使用
The WSAStartup function initiates use of Ws2_32.dll by a process.

int WSAStartup(
WORD wVersionRequested,
LPWSADATA lpWSAData
);
Parameters
wVersionRequested
[in] Highest version of Windows Sockets support that the caller can use. The high-order byte specifies the minor version (revision) number; the low-order byte specifies the major version number.
lpWSAData
[out] Pointer to the WSADATA data structure that is to receive details of the Windows Sockets implementation.
mattrew 2002-09-29
  • 打赏
  • 举报
回复
当然可以了 !
不是编译环境的问题
因为你是抄写的程序 你看好了 程序是什么平台下写的 我看你的程序是在
unix下的程序 你把头文件改成unix 的标准头文件就可以了

69,373

社区成员

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

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