您的位置:首页 > 理论基础 > 计算机网络

linux下tcp,udp,icmp小例子

2013-11-25 22:08 218 查看
linux下tcp,udp,icmp小例子

Tcp的



客户端
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>

#define MAXLINE 80
int port = 8000;

int main(int argc, char *argv[])
{
  struct sockaddr_in pin;
  int sock_fd;
  char buf[MAXLINE];
  char str[MAXLINE];
  int n;

  signal(SIGPIPE,SIG_IGN);

  bzero(&pin, sizeof(pin));
  pin.sin_family = AF_INET;
  inet_pton(AF_INET, argv[1], &pin.sin_addr);
  pin.sin_port = htons(port);
  
  sock_fd = socket(AF_INET, SOCK_STREAM, 0);
  n=connect(sock_fd, (void *)&pin, sizeof(pin));
  if (-1 == n)
  {
     perror("call connect");
     exit(1);
  }
  while(NULL != fgets(str,MAXLINE, stdin))
  {
    write(sock_fd, str, strlen(str)+1);
    n=read(sock_fd, buf, MAXLINE);
    if (0 == n)
      printf("the othere side has been closed.\n");
    else
      printf("receive from server:%s\n",buf);
  }
  close(sock_fd);
  return 0;
}

服务器端
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>

#define MAXLINE 8800
int port = 8000;

int main(void)
{
    struct sockaddr_in sin;
    struct sockaddr_in pin;
    int listen_fd;
    int conn_fd;
    int sock_fd;
    int nready;
    int maxi;
    int max;
    int client[FD_SETSIZE];
    int address_size = sizeof(pin);
    char buf[MAXLINE];
    char str[INET_ADDRSTRLEN];
    int i;
    int len;
    int n;
    int ret;

    bzero(&sin, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = INADDR_ANY;
    sin.sin_port = htons(port);

    signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, SIG_IGN);

    listen_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == listen_fd)
    {
        perror("call to socket");
        exit(1);
    }
    n = bind(listen_fd, (struct sockaddr *)&sin, sizeof(sin));
    if (-1 == n)
    {
        perror("call to bind");
        exit(1);
    }
    n = listen(listen_fd, 20);
    if (-1 == n)
    {
        perror("call to listen");
        exit(1);
    }
    printf("Accepting connections...\n");

    while(1)
    {
        conn_fd = accept(listen_fd, (struct sockaddr *)&pin, &address_size);

        n = fork();
        if (-1 == n){
            perror("call to fork");
            exit(1);
        }

        else if (0 == n)
        {
            close(listen_fd);
            while(1)
            {
                memset(buf,'\0',MAXLINE);
readagain:
                ret = read(conn_fd,buf,MAXLINE);
                printf("I read %d Byte!\n",ret);

                if (-1 == ret){
                    if (errno == EINTR){
                        goto readagain;
                    }else{
                        perror("call to read");
                        exit(1);
                    }
                } else if (0 == ret){
                    printf("the other side has been closed.\n");
                    break;
                }

                printf("you ip is %s at port %d:%s\n",
                     inet_ntop(AF_INET, &pin.sin_addr,str,sizeof(str)),
                     ntohs(pin.sin_port),buf);

                /*    len = strlen(buf);
                for (i = 0; i < len; i++)
                {
                    buf[i] = toupper(buf[i]);
                }

writeagain:
                ret = write(conn_fd, buf, len+1);
                printf("I write %d Byte!\n",ret);

                if (-1 == ret){
                    if (errno == EINTR){
                        goto writeagain;
                    } else {
                        perror("call to write!");
                        break;
                    }
                    }*/
            }// end while
            
            ret = close(conn_fd);

            if (-1 == ret){
                perror("call close");
                return -1;
            }
            exit(0);
        }
    }
    return 0;
}




Udp的



icmp的



#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
//#include <linux/icmp.h>
#include <strings.h>
#include <netinet/ip_icmp.h>
#include <stdlib.h>

void send_echo_req(int sockfd, struct sockaddr_in *dstaddr);  
uint16_t in_cksum(uint16_t *addr, int len);  
void recv_echo_reply(int sockfd);  

void err_sys(const char *errmsg)  
{
    perror(errmsg);
    exit(1);  
}

int main(int argc, char **argv)  
{
    int sockfd;
    struct sockaddr_in dstaddr;  

    if ((sockfd = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) == -1)
        err_sys("socket");

    bzero(&dstaddr, sizeof(dstaddr));
    dstaddr.sin_family = AF_INET;
    dstaddr.sin_port = htons(0);

    if (inet_pton(AF_INET, argv[1], &dstaddr.sin_addr) <= 0)
        err_sys("inet_pton");

    send_echo_req(sockfd, &dstaddr);
    recv_echo_reply(sockfd);
    exit(0);  
}  

void send_echo_req(int sockfd, struct sockaddr_in *dstaddr)  
{
    char buf[100];
    size_t len = sizeof(struct icmp);
    struct icmp *icmp;
    socklen_t dstlen = sizeof(struct sockaddr_in);

    bzero(buf, sizeof(buf));
    icmp = (struct icmp *)buf;
    icmp->icmp_type = ICMP_ECHO;//8
    icmp->icmp_code = 0;
    icmp->icmp_id = getpid();
    icmp->icmp_seq = 1;
    icmp->icmp_cksum = in_cksum((uint16_t *) icmp, sizeof(struct icmp));
    if (sendto(sockfd, buf, len, 0, (struct sockaddr *)dstaddr, dstlen) == -1)
        err_sys("sendto");  
}

void recv_echo_reply(int sockfd)  
{
    char buf[100];
    ssize_t n;
    struct ip *ip;
    struct icmp *icmp;
    while (1) {
        alarm(5); /* set timeout */
        if ((n = read(sockfd, buf, sizeof(buf))) == -1)
            err_sys("read");
        ip = (struct ip *)buf;

        if (ip->ip_p != IPPROTO_ICMP) {
            fprintf(stderr, "protocol error.");
            exit(1);
        }

        icmp = (struct icmp *)(buf + sizeof(struct ip));

        if (icmp->icmp_type == ICMP_ECHOREPLY) {
            if (icmp->icmp_id != getpid()) {
                fprintf(stderr, "not this process.");
                exit(1);
            } else {
                printf("destination host is alive.\n");
                break;
            }
        }
    }  
}

uint16_t in_cksum(uint16_t *addr, int len)  
{
    int nleft = len;
    uint32_t sum = 0;
    uint16_t *w = addr;
    uint16_t answer = 0;
    while (nleft > 1) {
        sum += *w++;
        nleft -= 2;
    }  

    if (nleft == 1) {
        *(unsigned char *)(&answer) = *(unsigned char *)w ;
        sum += answer;
    }

    sum = (sum >> 16) + (sum & 0xffff);
    sum += (sum >> 16);
    answer = ~sum;
    return(answer);  
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: