繁体   English   中英

使用命令行参数进行端口号和IP地址的套接字编程

[英]Socket Programming using command line arguments for port number and IP address

以下代码将命令行参数作为输入,并使套接字准备好侦听来自客户端的传入数据包,但是由于通过命令行输入的端口号未获得相同的提要,因此它在某个阶段没有停止运行,

请指导可能的错误

    #include <stdio.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <string.h>
    #include <stdlib.h>
    #include "p8log.h"
    #include <errno.h>


    #define FIRST_SIZE 1
    #define SECOND_SIZE 6
    #define THIRD_SIZE 16


    int main(int argc, char* argv[])
    {
           /*some code*/
 if (fd != NULL)
        {


                struct sockaddr_in serverAddr, clientAddr;
                struct sockaddr_storage serverStorage;
                socklen_t addr_size, client_addr_size;


                /*Create UDP socket*/
                udpSocket = socket(PF_INET, SOCK_DGRAM, 0);
                if (udpSocket==-1)
                        LERR("Error in creating the socket with the error number <%s>",strerror(errno) );

                /*Configure settings in address struct*/
                serverAddr.sin_family = AF_INET;
                serverAddr.sin_port = htons((int)*PORT);
                serverAddr.sin_addr.s_addr = inet_addr(IPADDR);
                memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);

                /*Bind socket with address struct*/

    return 0;
}                           

Execution of the program:
./a.out 11111 127.0.0.1


 Output:
Arg Count=3
Arguments are=./UDPserver,11111,127.0.0.1
port num=11111
IP ADDR=127.0.0.1

-------------------------------------------------- -----------------

客户端代码:

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


#define PORT 11111
#define IPADDR "127.0.0.1"


int main(){
  /*some code*/
}

在您的服务器中, PORTchar*

当您传递“ 11111”时, *PORT (aka PORT[0] )为'1' ,而(int)*PORT最有可能为49。

您需要将其转换为整数,例如使用atoi

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM