c 寫cgi 與socket通訊

來源:互聯網
上載者:User
伺服器端:

int sock()

{

int port=7777;

struct sockaddr_in sin;

struct sockaddr_in pin;

int sock_fp;

int temp_sock_fp;

int size_of_addr;

char *msg="hello internet!"

char buff[2561];



sock_fp = socket(AF_INET,SOCK_STREAM,0);

if(sock_fp==-1)

{

perror("socket");

exit(1);

}

bzero(&sin,sizeof(sin));

sin.sin_family=AF_INET;

sin.sin_addr.s_addr=INADDR_ANY;

sin.sin_port = htons(port);


if(bind(sock_fp,(struct sockaddr *)&sin,sizeof(sin))==-1)

{

perror("bind!");

exit(1);

}

if(listen(sock_fp,20)==-1)

{

perror("listen!");

exit(1);

}

printf("write to recive:\n");

while(1)

{


temp_sock_fp=accept(sock_fp,(struct sockaddr *)&pin,&size_of_addr);


if(temp_sock_fp==-1)

{

perror("accept!");

exit(1);

}

if(recv(temp_sock_fp,buff,sizeof(buff),0)==-1)

{

perror("recv");

exit(1);

}

printf("recv:%x\n",buf);

webdeal(WebServerComm.currentRead);

if(send(temp_sock_fp,msg.currentRead,sizeof(msg),0)==-1)

{

perror("send");

exit(1);

}

close(temp_sock_fp);

}


}


用戶端:

#include <stdio.h>

#include "cgic.h"

#include <string.h>

#include <stdlib.h>

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <netdb.h>

#include <stdio.h>

#include <unistd.h>

int cgiMain()

{

cgiHeaderContentType("text/html");

Sock();

return 0;

}

int Sock()

{

int sock_fp;

struct sockaddr_in pin;

struct hostent *server_host_name;

char *msg="ok,socket!";

char buff[2561];


char *host_name = "192.168.2.79";

int port=7777;


server_host_name = gethostbyname(host_name);

if(server_host_name==0) {

perror("can not resolving localhost\n");

exit(1);

}

bzero(&pin,sizeof(pin));

pin.sin_family = AF_INET;

pin.sin_addr.s_addr = htonl(INADDR_ANY);

pin.sin_port = htons(port);

sock_fp= socket(AF_INET, SOCK_STREAM, 0);

if(sock_fp==-1){

perror("cannot open socket ");

exit(1);

}

if(connect(sock_fp, (void *)&pin, sizeof(pin))==-1)

{

perror("con not connecting to server\n");

}



if(send(sock_fp,msg,sizeof(msg),0)==-1)

{

perror("can not send");

exit(1);

}

if(recv(sock_fp,buff,sizeof(buff),0)!=-1)

{

printf("buff=%s\n",buff);


}

else

{

perror("can not recv\n");

exit(1);

}

close(sock_fp);


}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.