C套接字 - 使用参数

时间:2016-06-02 14:13:59

标签: c sockets

我正在尝试使用套接字实现客户端/服务器程序。当我使用地址和端口的默认参数时,它工作正常。但是当我尝试使用主参数设置它们时,客户端返回“网络无法访问”。我该如何解决?

client.c

int main(int argc , char *argv[]) {
int sock, opcao;
struct sockaddr_in server;
char message[MAX_BUFFER] , server_reply[MAX_BUFFER], lista[MAX_BUFFER];

//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
    printf("Could not create socket");
}
//puts("Socket created");

server.sin_addr.s_addr = INADDR_ANY;
server.sin_family = AF_INET;
server.sin_port = htons( 8888 );

if (argc > 2) {
    server.sin_addr.s_addr = inet_addr(argv[1]);
    server.sin_port = htons(atoi(argv[2]));
}

//Connect to remote server

if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
    perror("connect failed. Error");
    return 1;
}

server.c

#include <stdio.h>
#include <string.h>   //strlen
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>   //close
#include <arpa/inet.h>    //close
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/time.h> //FD_SET, FD_ISSET, FD_ZERO macros

#define TRUE   1
#define FALSE  0
#define PORT 8888
#define MAX_CONNECTIONS 3

typedef struct TipoCliente {
    int socket;
    char apelido[100];
    char ip[20];
    int porta;
    int status;
} TipoCliente;

int main(int argc , char *argv[]) {
    int opt = TRUE;
    int master_socket, addrlen, new_socket, max_clients = MAX_CONNECTIONS, activity, i, j, valread, sd;
    TipoCliente clientes[MAX_CONNECTIONS];
    int max_sd;
    char *message = (char *)malloc(1025 * sizeof(char));
    struct sockaddr_in address;
    char EOS = '\0';
    char *primeiroN;
    char buffer[1025], aux[1025];  //data buffer of 1K

    //set of socket descriptors
    fd_set readfds;

    //a message
    strcpy(message, "Bem-vindo ao chat! O que voce deseja fazer?\n\n1. Solicitar inscricao no chat\n2. Atualizar seu status\n3. Receber lista de usuarios disponiveis\n4. Cancelar inscricao no chat\n");

    //initialise all client_socket[] to 0 so not checked
    for (i = 0; i < max_clients; i++)
    {
        clientes[i].socket = 0;
    }

    //create a master socket
    if( (master_socket = socket(PF_INET , SOCK_STREAM , 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    //set master socket to allow multiple connections , this is just a good habit, it will work without this
    if( setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 )
    {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }

   //valores default para o servidor
   address.sin_family = AF_INET;
   address.sin_addr.s_addr = INADDR_ANY;
   address.sin_port = htons(PORT);

   if (argc > 1) {
       address.sin_port = htons(atoi(argv[1]));
   }
   printf("Listener on port %d \n", address.sin_port);

在命令行上我正在使用:

客户端:./ client localhost 8888

服务器:./ server 8888

1 个答案:

答案 0 :(得分:1)

许多用户发布了,我的错误是客户端参数。用IP地址替换localhost,例如127.0.0.1,它可以工作。