您的位置:首页 > 其它

socket 访问百度

2016-06-14 18:10 387 查看
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/time.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>

#define BUFSIZE 1024*2014
#define PORT 80
#define IPSTR "61.135.169.125"
#define DOMAIN "www.baidu.com"

int Read(int fd, char *buf, int count) {
int nread, totlen = 0;

while (totlen != count) {
nread = read(fd, buf, count - totlen);
if (nread == 0)
return totlen;
if (nread == -1)
return -1;
totlen += nread;
buf += nread;
}

return totlen;
}

int Write(int fd, char *buf, int count) {
int nwritten, totlen = 0;
while (totlen != count) {
nwritten = write(fd, buf, count - totlen);
if (nwritten == 0)
return totlen;
if (nwritten == -1)
return -1;
totlen += nwritten;
buf += nwritten;
}
return totlen;
}

int Socket(const char *host, int clientPort)
{
int sock;
unsigned long inaddr;
struct sockaddr_in ad;
struct hostent *hp;

memset(&ad, 0, sizeof(ad));
ad.sin_family = AF_INET;

inaddr = inet_addr(host);
if (inaddr != INADDR_NONE)
memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
else
{
hp = gethostbyname(host);
if (hp == NULL)
return -1;
memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
}
ad.sin_port = htons(clientPort);

sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
return sock;
if (connect(sock, (struct sockaddr *)&ad, sizeof(ad)) < 0)
return -1;
return sock;
}

int main(int argc, char **argv)
{
int sockfd, ret, i, h;

struct sockaddr_in servaddr;
char str1[BUFSIZE] = {0};
char str2[BUFSIZE];
char buf[BUFSIZE];

socklen_t len;
fd_set   t_set1;
struct timeval  tv;

int port = 80;
sockfd = Socket(DOMAIN, port);
if(-1 == sockfd)
{
printf("create socket error \n");
return -1;
}
//printf("create socket ok %s fd = %d\n", DOMAIN, sockfd);

strcat(str1, "GET / HTTP/1.1\r\n");
strcat(str1, "Host: www.baidu.com\r\n");
strcat(str1, "\r\n\r\n");

int writecount = Write(sockfd, str1, strlen(str1));
//printf("writecount = %d\n", writecount);

FD_ZERO(&t_set1);
FD_SET(sockfd, &t_set1);

while(1)
{
sleep(2);
tv.tv_sec= 0;
tv.tv_usec= 0;
h = 0;
//printf("--------------->1");
h= select(sockfd +1, &t_set1, NULL, NULL, &tv);
//printf("--------------->2");

if (h == 0)
{
continue;
}

if (h < 0)
{
close(sockfd);
printf("select error\n");
return -1;
}

if (h > 0)
{
int n = Read(sockfd, buf, BUFSIZE);
//printf("Response from server: size = %d\n", n);
if(n != 0)
{
printf("%s\n", buf);
}
}
}

close(sockfd);
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: