当前位置: 代码迷 >> PHP >> C与php socket通讯
  详细解决方案

C与php socket通讯

热度:167   发布时间:2012-09-17 12:06:52.0
C与php socket通信

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <sys/types.h>

#include <unistd.h>

#include <arpa/inet.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <netdb.h>

#include <errno.h>

#define PORT 80

#define SERVER_IP "192.168.1.21"

?

int main(int argc,char *argv[])

{

int ii,i,serverSocket;

struct sockaddr_in clientAddr;

char buffer[4096];

serverSocket =socket(AF_INET,SOCK_STREAM,0);

if(serverSocket==-1)

? {

?printf("Invalid socket\n");

?exit(1);

? }

bzero(&clientAddr,sizeof(clientAddr));?

clientAddr.sin_family=AF_INET;

clientAddr.sin_port=htons(PORT);

clientAddr.sin_addr.s_addr=inet_addr(SERVER_IP);

if(connect(serverSocket,&clientAddr,sizeof(clientAddr))<0)

{

perror("connect");

exit(1);

}

strcpy(buffer,"GET / HTTP/1.1\nHost:192.168.1.21\n\n");

printf("\n%s\n",buffer);

if(send(serverSocket,buffer,sizeof(buffer),0)<0)

{

perror("send error");

exit(1);

}

ii=(int)recv(serverSocket,buffer,sizeof(buffer),0);

printf("\nrev=%d length\n",ii);

for(i=0;i<ii;i++)

{

printf("%c",buffer[i]);

}

return 1;

}


  相关解决方案