zoukankan      html  css  js  c++  java
  • 向指定服务器的指定端口发送UDP包

    //功能:读取文件文件,向指定服务器的指定端口发送UDP包,
    //2015.9.26 OK

    #include <stdio.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <netdb.h>
    #include <string.h>

    //#define SERVER_PORT 8000
    int SERVER_PORT = 8000;

    int GetServerAddr(char * addrname,char *addrport)
    {
    char szTemp[512]={};
    char IPaddr[512]={};
    char port[512]={};
    char *cfa;

    FILE *file_fa = fopen("./send.conf","r+");
    if(file_fa==NULL) //如果失败了
    {
    printf("open send.conf错误! ");
    exit(1); //中止程序
    }

    if((fgets(szTemp,255,file_fa)) != NULL ) //每次读一行
    {
    printf("szTemp=%s ",szTemp);

    cfa = strtok(szTemp, " ");
    sprintf(port,"%s",cfa);
    cfa = strtok(NULL, " ");
    sprintf(IPaddr,"%s",cfa);
    cfa = strtok(NULL, " ");
    sprintf(port,"%s",cfa);

    // printf("IPaddr=%s port=%s ",IPaddr,port);

    }
    sprintf(addrname,"%s",IPaddr);
    sprintf(addrport,"%s",port);
    fclose(file_fa);
    return 1;
    }
    int main(int argc,char **argv)
    {
    int cli_sockfd;
    int len;
    socklen_t addrlen;
    char seraddr[14];
    char serport[14];
    struct sockaddr_in cli_addr;
    char buffer[256];

    GetServerAddr(seraddr,serport);
    printf("GetServerAddr=%s,port=%s ",seraddr,serport);

    /* 建立socket*/
    cli_sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if(cli_sockfd<0)
    {
    printf("I cannot socket success ");
    return 1;
    }

    /* 填写sockaddr_in*/
    addrlen=sizeof(struct sockaddr_in);
    bzero(&cli_addr,addrlen);
    cli_addr.sin_family=AF_INET;
    cli_addr.sin_addr.s_addr=inet_addr(seraddr);//将字符串转换为32位二进制网络字节序的IPV4地址
    //cli_addr.sin_addr.s_addr=htonl(INADDR_ANY);
    cli_addr.sin_port=htons( atoi(serport) );//主机字节顺序转化为网络字节顺序
    // cli_addr.sin_port=htons(SERVER_PORT);

    bzero(buffer,sizeof(buffer));
    /* 从标准输入设备取得字符串*/
    // len=read(STDIN_FILENO,buffer,sizeof(buffer));
    sprintf(buffer,"%s","nihao");
    len = sizeof(buffer)+1;
    /* 将字符串传送给server端*/
    while(1)
    {
    printf("sendword=%s ",buffer);
    sendto(cli_sockfd,buffer,len,0,(struct sockaddr*)&cli_addr,addrlen);
    sleep(2);
    }
    /* 接收server端返回的字符串*/
    len=recvfrom(cli_sockfd,buffer,sizeof(buffer),0,(struct sockaddr*)&cli_addr,&addrlen);
    //printf("receive from %s ",inet_ntoa(cli_addr.sin_addr));
    printf("receive: %s",buffer);
    close(cli_sockfd);
    }

  • 相关阅读:
    elasticsearch 数据迁移
    elasticsearch使用简介 -安装篇
    docker 使用笔记
    PHP 全局变量
    做人做事需牢记20条原则
    MYSQL 存储引擎概述
    postgresql常用命令
    ORACLE 清理SYSAUX表空间
    sqlserver数据库的启动
    postgressql启动与关闭
  • 原文地址:https://www.cnblogs.com/zhouhbing/p/4841095.html
Copyright © 2011-2022 走看看