这是在windows上运行的 为什么read会返回-1 服务端己写好了 connect没有问题。
#include <stdio.h>
#include <io.h>
#include <winsock2.h>
int main()
{
int sockfd, n, ret;
WORD ver;
WSADATA data;
ver = MAKEWORD( 2, 2 );
ret = WSAStartup( ver, &data );
char recvline[100], addr[] = “127.0.0.1”;
struct sockaddr_in servaddr;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf(“sock open error!\n”);
return 0;
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(13);
servaddr.sin_addr.S_un.S_addr = inet_addr(addr);
if((ret = connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr))) < 0)
{
ret = WSAGetLastError();
printf(“connect error!”);
return 0;
}
while((n = read(sockfd, recvline, 100)) > 0)
{
recvline[n] = 0;
printf(recvline);
}
if(n < 0)
perror(“read”);
getchar();
return 0;
}
#include <stdio.h>
#include <io.h>
#include <winsock2.h>
int main()
{
int sockfd, n, ret;
WORD ver;
WSADATA data;
ver = MAKEWORD( 2, 2 );
ret = WSAStartup( ver, &data );
char recvline[100], addr[] = “127.0.0.1”;
struct sockaddr_in servaddr;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf(“sock open error!\n”);
return 0;
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(13);
servaddr.sin_addr.S_un.S_addr = inet_addr(addr);
if((ret = connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr))) < 0)
{
ret = WSAGetLastError();
printf(“connect error!”);
return 0;
}
while((n = read(sockfd, recvline, 100)) > 0)
{
recvline[n] = 0;
printf(recvline);
}
if(n < 0)
perror(“read”);
getchar();
return 0;
}
解决方案
20
servaddr.sin_port = htons(13);
改个大于1024的端口试试
改个大于1024的端口试试
20
建议先参考MSDN98中自带的socket例子代码。
MSDN98_1.ISO http://pan.baidu.com/s/1dDF41ix, MSDN98_2.ISO http://pan.baidu.com/s/1bnGo0Vl
MSDN98\SAMPLES\VC98\SDK\NETDS\WINSOCK\SIMPLE\SIMPLES.C
MSDN98\SAMPLES\VC98\SDK\NETDS\WINSOCK\SIMPLE\SIMPLEC.C
MSDN98_1.ISO http://pan.baidu.com/s/1dDF41ix, MSDN98_2.ISO http://pan.baidu.com/s/1bnGo0Vl
MSDN98\SAMPLES\VC98\SDK\NETDS\WINSOCK\SIMPLE\SIMPLES.C
MSDN98\SAMPLES\VC98\SDK\NETDS\WINSOCK\SIMPLE\SIMPLEC.C