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

时间:2016-03-03 09:24:37

标签: c sockets command-line-arguments

下面的代码将命令行参数作为输入,并使套接字准备好侦听来自客户端的传入数据包,但是它在某个阶段没有运行,因为通过命令行输入的端口号没有获取同样,

请指出可能存在的错误

    #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*/
}

1 个答案:

答案 0 :(得分:2)

在您的服务器中,PORTchar*

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

您需要使用例如atoi转换为整数。