日期:2014-05-16  浏览次数:20730 次

VC与linux下socket通讯
VC下的server端程序和linux下的client端程序, 不知道为什么通讯不了,知道的说下,谢谢,代码如下:
server端pc下VC编译
#include <windows.h>
#include <stdio.h>
#pragma comment (lib,"WS2_32.lib")
#define USERPORT 10001
#define HOST_IP_ADDR "127.0.0.1"

main(int argc,char *argv[])
{
printf("begin at main \n");
char buf[128];
SOCKET s,ns;
struct sockaddr_in client;
struct sockaddr_in server;
int namelen,pklen;
int status;
WSADATA wsd;

if((status=WSAStartup(MAKEWORD(2,2),&wsd))!=0)
{
perror("wsastartup() failed:");
exit(1);
}
  printf("WSAStartup end \n");
//if((s=socket(AF_INET,SOCK_STREAM,0))< 0)
if((s=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP))< 0)
{
perror("socket failed :");
exit(1);
}
  printf("socket end \n");
ZeroMemory(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(USERPORT);
server.sin_addr.s_addr=htons(INADDR_ANY);
if(bind(s,(struct sockaddr *)&server,sizeof(server))<0)
{
perror("bind() failed:");
exit(2);
}
printf("bind end \n");
if(listen(s,4)!=0)
{
perror("listen()failed :");
exit(3);
}
printf("listen end \n");
while(1)
{
namelen=sizeof(client);
if((ns=accept(s,(struct sockaddr*)&client,&namelen))==-1)
{
perror("accept()failed:");
exit(4);
}
printf("accept successful\n");
for(;;)
{
if((pklen=recv(ns,buf,128,0))<0)
{
perror("recv() failed:");
exit(5);
}
else
if(pklen==0)
{
printf("recv():return FAILED,connected is shut down");
break;
}
else
printf("recv():return success,packet length=%d context is %s/n",pklen,buf);
  
Sleep(1);
printf("the buf is %s/n",buf);
if(send(ns,buf,128,0)<0)
{
perror("send() failed:");
break;
}
else
printf("send() return success packet length is %d/n",pklen);
}
}
closesocket(ns);
closesocket(s);
printf("server ended successfully/n");
}

client端 linux下gcc编译
#include <netinet/in.h> // for sockaddr_in
#include <sys/types.h> // for socket
#include <sys/socket.h> // for socket
#include <stdio.h> // for printf
#include <stdlib.h> // for exit
#include <string.h> // for bzero
#include <pthread.h>
#include <sys/errno.h> // for errno
#include <fcntl.h> //for open

#define HELLO_WORLD_SERVER_PORT 6666 
#define BUFFER_SIZE 1024
int ConnectToServer(char * serverip)
{
//设置一个socket地址结构client_addr,代表客户机internet地址, 端口
struct sockaddr_in client_addr;
bzero(&client_addr,sizeof(client_addr)); //把一段内存区的内容全部设置为0
client_addr.sin_family = AF_INET; //internet协议族
client_addr.sin_addr.s_addr = htons(INADDR_ANY);//INADDR_ANY表示自动获取本机地址
client_addr.sin_port = htons(0); //0表示让系统自动分配一个空闲端口
//创建用于internet的流协议(TCP)socket,用client_socket代表客户机socket
int client_socket = socket(AF_INET,SOCK_STREAM,0);
if( client_socket < 0)
{
printf("Create Socket Failed! \n");
return -1;
}
//把客户机的socket和客户机的socket地址结构联系起来
if( bind(client_socket,(struct sockaddr*)&client_addr,sizeof(client_addr)))
{
printf("Clie