前几个星期在做一个网络编程实验:爬取一个包含几十万网页的服务器,并分析各个网页之间的联系,计算PageRank值等。
下面贴一下建立socket链接的代码,这部分应该不难。在Linux下使用C语言实现:
/*
文件名:network.h
作者:xyw
*/
#ifndef _NETWORK_H_
#define _NETWORK_H_
#ifndef _HTTPCLIENT_H_
#define _HTTPCLIENT_H_
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<sys/wait.h>
#include<netdb.h>
#include<iconv.h>
int open_tcp(char *hostname,int port); //建立一个到远程服务器的socket连接
int nsend(int sockfd,char *msg); //发送字节到网络
int nrecv(int sockfd,char *buf,int length);//发送网络字节流
int recv_line(int sockfd,char *buf);//从socket接收一行以回车键结束
void nclose(int sockfd);//关闭socket
#endif
#endif
/*****
** network.c
** - implements the methods declared in network.h
** - 对网络socket的收发进行封装
** - 作者:xyw
*/
#include "network.h"
#include "http_client.h"
//建立一个到远程服务器的socket连接
int open_tcp(char *hostname,int port)
{
int clientfd;
/*
hostent,该结构记录主机的信息,包括主机名、别名、地址类型、地址长度和地址列表。
struct hostent {
char *h_name; 地址的正式名称。
char **h_aliases; 空字节-地址的预备名称的指针
int h_addrtype; 地址类型;