C# winsocket para C- com outra alguma urgencia

hugo89

Power Member
Boas

Estou a precisar de ajuda em programação de C# e C.
Tenho um programa em C# e queria que enviasse para um socket do windows três variáveis que serão lidas pelo programa feito em C.
Obs.: Os dois programas correm ao mesmo tempo com escrita e leitura em simultâneo. É possivel não dar erro??
Preciso de saber o código em C# para escrever no socket e de saber como posso ler o mesmo socket em C.

Obrigado, cumprimentos.
 
Última edição:
outra forma de consguir mudar as variaveis

Alguém me podia dizer qual o melhor método, para além deste e que se adeque a minha necessidade?
Eu só queria saber a parte dos códigos em C# e C que me permitissem enviar e ir buscar as variaveis.

Origado
 
a comunicação entre sockets realiza-se usando protocolos, ou seja não interessa como é que está implementado o cliente ou o servidor, podem estar cada um na sua linguagem mas se seguirem os protocolos então há comunicação sem problemas.

ok, vou supor que o cliente é o que está em C# e o servidor é o que está em C:
ao trabalhar com sockets, seja como servidor ou como cliente é sempre a mesma coisa, defines o tipo de socket que queres, o endereço e porta a ligar ou a receber, crias o socket, fazes bind dele a porta e depois ficas a "ouvir" e a "aceitar" ligações (listen() e accept() no caso de ser servidor) ou então connect() no caso de cliente.
e pronto o mais dificil já está, depois de haver ligação é so usar sends() e receives() seja lá como estiver implementado na biblioteca/linguagem/etc que estejas a usar.

server em C (com o maior numero possivel de comments):
Código:
#include <socket.h> //equivalente em windows é <winsock.h> ou <winsock2.h> não tenho a certeza, mas é facil ver isso na net

(...)

sockaddr_storage their_addr; //informações do cliente que se vai ligar
socklen_t addr_size; //tamanho da struct com as infos do cliente
addrinfo hints, *res; //hints: setup da nossa ligação, *res: resposta para getaddrinfo()
int sockfd, new_fd; //socket descriptor do server e do cliente a ligar-se

memset( &hints, 0, sizeof(hints) );
hints.ai_family = AF_UNSPEC; //diz-lhe para usar IPv4 ou IPv6, o que estiver disponivel
hints.ai_socktype = SOCK_STREAM; //quero streams TCP
hints.ai_flags = AI_PASSIVE; //diz ao socket para preencher o endereço IP automaticamente, vai ser localhost

getaddrinfo( NULL, 300, &hints, &res ); //NULL porque é servidor, 300 = porta, pode ser a que quiseres

//cria o socket usando as opçoes que definimos antes
sockfd = socket( res->ai_family, res->ai_socktype, res->ai_protocol );

//faz bind desse socket ao endereço e porta passada anteriormente
bind( sockfd, res->ai_addr, res->ai_addrlen );

//fica a "ouvir" ligações, o 2º argumento é o numero maximo de ligações que queres aceitar
listen( sockfd, 1 );

//aceita a ligação
addr_size = sizeof(their_addr);
new_fd = accept( sockfd, (sockaddr*)&their_addr, &addr_size );

//e pronto, a parte mais complicada já está, agora é so receber e enviar dados
//1º argumento socket de onde se vai ler, 2º buffer com os dados, 3º tamanho maximo, 4º flags (pode ser 0)
//atenção embora muitas implementações escondam isso (java, .net, etc) sockets so podem enviar/receber 1024 bytes de cada vez
typedef BYTE char;
BYTE buffer[1024];

recv( sockfd, (BYTE*)buffer, 1024, 0 );

//buffer agora tem os dados que quiseste, aquilo é cast de void* portanto pode ser qq tipo de dados que queiras.

(...)
//fechar sockets e shutdown:
close(sockfd);
close(new_fd);

pronto o server já está, agora falta o cliente em C#
Código:
using System.Net.Sockets;

(...)

TCPClient client = new TCPClient( "mm_endereço_usado_no_server", 300 ); //300 é a porta do server
string dados = "olá servidor!"; //a nossa msg para o server
Stream socket_stream = client.GetStream(); //é por aqui que vamos comunicar.

//setup dos dados a transmitir, até porque queremos enviar como bytes:
ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba = asen.GetBytes( dados );

//escreve no stream do socket, ou seja envia msg.
stm.Write(ba,0,ba.Length);

(...)
client.Close();
e pronto, tentei ser o mais user-friendly possivel, se bem que o server que fiz só recebe, e o client só envia, fica como TPC meter o cliente tb a receber e o servidor tb a enviar =p

MUITO IMPORTANTE: http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html é O guia de programação de sockets, lê e relê, é virado para sockets em C mas ensina também a teoria sobre programação de sockets que se enquadra em todas as linguagens/bibliotecas.

PS: winsockets é praticamente igual a sockets em C, só o header é que é diferente e tem de se fazer uma chamada para WSAStartup() vê no msdn como se usa (é muito facil e só se chama uma vez).
 
Boas

Desde já agradeço a tua resposta, já estive a exprimentar o programa.
Em C#

ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba = asen.GetBytes( dados );

//escreve no stream do socket, ou seja envia msg.
stm.Write(ba,0,ba.Length);

teve que ficar da seguinte forma:

System.Text.ASCIIEncoding asen = new System.Text.ASCIIEncoding();
byte

stm.Write(ba, 0, ba.Length);

nesta linha da-me um erro a dizer que não sabe o que ó o stm, já exprimentei escrever mesmo stream e tmb nada.

no codigo em C, consigo meter os includes da seguinte forma:
#include<winsock.h>
#include<winsock2.h>

mas dá-me aspecto que dá erros em todas as instruções, porque ao fazer o relatório vai para a o código do ws2def.h e põe-se a dar erros.
 
tens razão não é stm, é socket_stream

socket_stream.Write( ba, 0, ba.Length );
porque socket_stream é o nome do Stream declarado mais em cima que foi buscar o Stream de comunicação com o client.GetStream();

quanto aos erros em C, tens de escrever aqui quais são mesmo, pq as funções de winsock são iguais as de POSIX, da biblioteca socket.h mesmo.

no entanto cheira-me a erros de linking, tas a linkar a biblioteca?
 
Sim tens razão, tem erros quanto ao linking
tive a ler o tuturial do link e tive tentar seguir as regras, mas não sei como se faz no vs2008, não tem lá a opção settings.
 
no vs2008 tens de ir a:
menu Project -> Project Properties -> Linker (mais em baixo) -> Input, nessa tab dentro de "Additional Dependencies" escreves: wsock32.lib
pronto ele assim linka a essa biblioteca.
 
se for como tenho o link para a biblioteca fica com os seguintes erros:
Código:
Error 1 error C2065: 'sockaddr_storage' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 15 winsocket
Error 2 error C2146: syntax error : missing ';' before identifier 'their_addr' c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 15 winsocket
Error 3 error C2065: 'their_addr' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 15 winsocket
Error 4 error C2275: 'socklen_t' : illegal use of this type as an expression c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 16 winsocket
Error 5 error C2146: syntax error : missing ';' before identifier 'addr_size' c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 16 winsocket
Error 6 error C2065: 'addr_size' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 16 winsocket
Error 7 error C2065: 'addrinfo' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 17 winsocket
Error 8 error C2146: syntax error : missing ';' before identifier 'hints' c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 17 winsocket
Error 9 error C2065: 'hints' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 17 winsocket
Error 10 error C2065: 'res' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 17 winsocket
Error 11 error C2100: illegal indirection c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 17 winsocket
Error 12 error C2143: syntax error : missing ';' before 'type' c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 18 winsocket
Error 13 error C2065: 'hints' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 20 winsocket
Error 14 error C2065: 'hints' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 20 winsocket
Error 15 error C2065: 'hints' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 21 winsocket
Error 16 error C2224: left of '.ai_family' must have struct/union type c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 21 winsocket
Error 17 error C2065: 'hints' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 22 winsocket
Error 18 error C2224: left of '.ai_socktype' must have struct/union type c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 22 winsocket
Error 19 error C2065: 'hints' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 23 winsocket
Error 20 error C2224: left of '.ai_flags' must have struct/union type c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 23 winsocket
Error 23 error C2065: 'hints' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 25 winsocket
Error 25 error C2065: 'res' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 25 winsocket
Error 28 error C2065: 'sockfd' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 28 winsocket
Error 29 error C2065: 'res' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 28 winsocket
Error 30 error C2223: left of '->ai_family' must point to struct/union c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 28 winsocket
Error 31 error C2065: 'res' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 28 winsocket
Error 32 error C2223: left of '->ai_socktype' must point to struct/union c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 28 winsocket
Error 33 error C2065: 'res' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 28 winsocket
Error 34 error C2223: left of '->ai_protocol' must point to struct/union c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 28 winsocket
Error 35 error C2198: 'socket' : too few arguments for call c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 28 winsocket
Error 36 error C2065: 'sockfd' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 31 winsocket
Error 37 error C2065: 'res' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 31 winsocket
Error 38 error C2223: left of '->ai_addr' must point to struct/union c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 31 winsocket
Error 39 error C2065: 'res' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 31 winsocket
Error 40 error C2223: left of '->ai_addrlen' must point to struct/union c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 31 winsocket
Error 41 error C2198: 'bind' : too few arguments for call c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 31 winsocket
Error 42 error C2065: 'sockfd' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 34 winsocket
Error 43 error C2065: 'addr_size' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 37 winsocket
Error 44 error C2065: 'their_addr' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 37 winsocket
Error 45 error C2065: 'new_fd' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 38 winsocket
Error 46 error C2065: 'sockfd' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 38 winsocket
Error 47 error C2065: 'sockaddr' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 38 winsocket
Error 48 error C2059: syntax error : ')' c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 38 winsocket
Error 49 error C2143: syntax error : missing ';' before 'type' c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 43 winsocket
Error 50 error C2275: 'BYTE' : illegal use of this type as an expression c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 44 winsocket
Error 51 error C2146: syntax error : missing ';' before identifier 'buffer' c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 44 winsocket
Error 52 error C2065: 'buffer' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 44 winsocket
Error 53 error C2109: subscript requires array or pointer type c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 44 winsocket
Error 54 error C2065: 'sockfd' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 46 winsocket
Error 55 error C2065: 'buffer' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 46 winsocket
Error 57 error C2065: 'sockfd' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 52 winsocket
Error 58 error C2065: 'new_fd' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 53 winsocket
 
no c# estou a ter um problema no
Código:
[SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]
TcpClient[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] client = [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]new[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] [/COLOR][/SIZE][SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]TcpClient[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000]( [/COLOR][/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"mm_endereço_usado_no_server"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000], 300 ); [/COLOR][/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//300 é a porta do server
[/COLOR][/SIZE][/COLOR][/SIZE]
´

que depois de executar manda um erro "Este anfitrião não é conhecido"

ou só posso executar o cliente depois de abrir o servidor??
 
se for como tenho o link para a biblioteca fica com os seguintes erros:
hmm, esses erros todos é quase de certeza porque estás a compilar como C, e C obriga a meter a keyword struct quando se declara variaveis que sejam structs
em vez de por exemplo:
sockaddr_storage their_addr;
tinha de ser
struct sockaddr_storage their_addr;

e o memso pro resto, o ideal seria compilar como C++, embora seja C não interessa C++ é backwards compatible com C e nesses pormenores é muito mais tolerante (muda o ficheiro de codigo para .cpp ou diz ao proprio compilador para compilar como C++).

ou só posso executar o cliente depois de abrir o servidor??
yep, e não te esqueças que o 1º argumento é o endereço aonde te queres ligar, se for no mm PC aonde etsá o servidor um "127.0.0.1" ou "localhost" chega.
 
Bem já tenho o codigo assim:
Código:
[SIZE=2][COLOR=#0000ff]
[SIZE=2][COLOR=#0000ff]#include[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]<winsock2.h>[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]#include[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]<ws2tcpip.h>[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]#include[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]<stdio.h>[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]#include[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]<stdio.h>[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]#include[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]<string.h>[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]/*#include <sys/types.h>[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]#include <sys/socket.h>[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]#include <netdb.h>[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]#include <arpa/inet.h>*/[/COLOR][/SIZE]
 
[SIZE=2][COLOR=#008000]/*[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]struct a {[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]int their_addr; //informações do cliente que se vai ligar[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]}sockaddr_storage;[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]struct b{[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]int addr_size; //tamanho da struct com as infos do cliente[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]}socklen_t;[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]//socklen_t addr_size; //tamanho da struct com as infos do cliente[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]struct c[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]{[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]int *res;[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]int ai_family;[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]int ai_socktype;[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]int ai_flags;[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]}hints;[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]}addrinfo;[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]*/[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]struct[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] a{[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] ai_family, ai_socktype, ai_flags, ai_protocol, ai_addrlen, ai_addr;[/SIZE]
[SIZE=2]};[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]struct[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] b {[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] addr_size; [/COLOR][/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//tamanho da struct com as infos do cliente[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]};[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]struct[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] c {[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] their_addr; [/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//informações do cliente que se vai ligar[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]};[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] main()[/COLOR][/SIZE]
[SIZE=2]{[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]struct[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] a hints;[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]struct[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] b socklen_t;[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]struct[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] c sockaddr_storage;[/SIZE]
 
 
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] *res; [/COLOR][/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//hints: setup da nossa ligação, *res: resposta para getaddrinfo()[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] sockfd, new_fd; [/COLOR][/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//socket descriptor do server e do cliente a ligar-se[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]memset( &hints, 0, [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]sizeof[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2](hints) );[/SIZE]
[SIZE=2]hints.ai_family = AF_UNSPEC; [/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//diz-lhe para usar IPv4 ou IPv6, o que estiver disponivel[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]hints.ai_socktype = SOCK_STREAM; [/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//quero streams TCP[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]hints.ai_flags = AI_PASSIVE; [/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//diz ao socket para preencher o endereço IP automaticamente, vai ser localhost[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]getaddrinfo( NULL, 300, &hints, &res ); [/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//NULL porque é servidor, 300 = porta, pode ser a que quiseres[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]//cria o socket usando as opçoes que definimos antes[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]sockfd = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol );[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//faz bind desse socket ao endereço e porta passada anteriormente[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]bind(sockfd, hints.ai_addr, hints.ai_addrlen);[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//fica a "ouvir" ligações, o 2º argumento é o numero maximo de ligações que queres aceitar[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]listen( sockfd, 1 );[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//aceita a ligação[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]socklen_t.addr_size = [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]sizeof[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2](sockaddr_storage.their_addr);[/SIZE]
[SIZE=2]new_fd = accept(sockfd, (sockaddr_storage*)&sockaddr_storage.their_addr, &socklen_t.addr_size);[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]/*e pronto, a parte mais complicada já está, agora é so receber e enviar dados[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]1º argumento socket de onde se vai ler, 2º buffer com os dados, 3º tamanho maximo, 4º flags (pode ser 0)[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]atenção embora muitas implementações escondam isso (java, .net, etc) sockets so podem enviar/receber 1024 bytes de cada vez*/[/COLOR][/SIZE]
 
[SIZE=2][COLOR=#008000]//typedef char BYTE;[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]char[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] buffer;[/COLOR][/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//[1024];[/COLOR][/SIZE]
 
[/COLOR][/SIZE][SIZE=2]ecv( sockfd, ([/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]char[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]*)buffer, 1024, 0 );[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//buffer agora tem os dados que quiseste, aquilo é cast de void* portanto pode ser qq tipo de dados que queiras.[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]//(...)[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]//fechar sockets e shutdown:[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]close(sockfd);[/SIZE]
[SIZE=2]close(new_fd);[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//(...)[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]//fechar sockets e shutdown:[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]close(sockfd);[/SIZE]
[SIZE=2]close(new_fd);[/SIZE]
[SIZE=2]}[/SIZE]

com os seguintes erros:

Código:
Error 7 error C2059: syntax error : ')' c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 73 winsocket
Error 8 error C2143: syntax error : missing ';' before 'type' c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 82 winsocket
Error 9 error C2065: 'buffer' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 84 winsocket

Podes me dizer se tou a ir bem?
 
Nao quria editar o post anterior pa ver os erros feitos
entretanto já modifiquei e ficou assim:
Código:
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]#include[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]<winsock2.h>[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]#include[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]<ws2tcpip.h>[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]#include[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]<stdio.h>[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]#include[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]<stdio.h>[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]#include[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]<string.h>[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]#include[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]<winsock.h>[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]/*#include <sys/types.h>[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]#include <sys/socket.h>[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]#include <netdb.h>[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]#include <arpa/inet.h>*/[/COLOR][/SIZE]
 
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]typedef[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]char[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] BYTE;[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]struct[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] a{[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] ai_family, ai_socktype, ai_flags, ai_protocol, ai_addrlen, ai_addr;[/SIZE]
[SIZE=2]};[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]struct[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] b {[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] addr_size; [/COLOR][/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//tamanho da struct com as infos do cliente[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]};[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]struct[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] c {[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] their_addr; [/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//informações do cliente que se vai ligar[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]};[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] main()[/COLOR][/SIZE]
[SIZE=2]{[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]struct[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] a hints, *res; [/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//hints: setup da nossa ligação, *res: resposta para getaddrinfo()[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]struct[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] b socklen_t;[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]struct[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] c sockaddr_storage;[/SIZE]
 
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#000000] sockfd, new_fd; [/COLOR][/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//socket descriptor do server e do cliente a ligar-se[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]BYTE buffer[1024];[/SIZE]
[SIZE=2]memset( &hints, 0, [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]sizeof[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2](hints) );[/SIZE]
[SIZE=2]hints.ai_family = AF_UNSPEC; [/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//diz-lhe para usar IPv4 ou IPv6, o que estiver disponivel[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]hints.ai_socktype = SOCK_STREAM; [/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//quero streams TCP[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]hints.ai_flags = AI_PASSIVE; [/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//diz ao socket para preencher o endereço IP automaticamente, vai ser localhost[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]getaddrinfo( NULL, 300, &hints, &res ); [/SIZE][SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//NULL porque é servidor, 300 = porta, pode ser a que quiseres[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]//cria o socket usando as opçoes que definimos antes[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]sockfd = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol );[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//faz bind desse socket ao endereço e porta passada anteriormente[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]bind(sockfd, hints.ai_addr, hints.ai_addrlen);[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//fica a "ouvir" ligações, o 2º argumento é o numero maximo de ligações que queres aceitar[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]listen( sockfd, 1 );[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//aceita a ligação[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]socklen_t.addr_size = [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]sizeof[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2](sockaddr_storage.their_addr);[/SIZE]
[SIZE=2]new_fd = accept(sockfd, &sockaddr_storage.their_addr, &socklen_t.addr_size);[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//new_fd = accept(sockfd, (sockaddr_storage*)&sockaddr_storage.their_addr, &socklen_t.addr_size)[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]/*e pronto, a parte mais complicada já está, agora é so receber e enviar dados[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]1º argumento socket de onde se vai ler, 2º buffer com os dados, 3º tamanho maximo, 4º flags (pode ser 0)[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]atenção embora muitas implementações escondam isso (java, .net, etc) sockets so podem enviar/receber 1024 bytes de cada vez*/[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]recv( sockfd, (BYTE*)buffer, 1024, 0 );[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//buffer agora tem os dados que quiseste, aquilo é cast de void* portanto pode ser qq tipo de dados que queiras.[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]printf([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"%c"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2], buffer);[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]//fechar sockets e shutdown:[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]//close(sockfd);[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]//close(new_fd);[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]close(sockfd);[/SIZE]
[SIZE=2]close(new_fd);[/SIZE]
[SIZE=2]}[/SIZE]

está a compilar, mas dá um erro no close, pk meti um ciclo for infinito, pa tar smpr a ler e esta a dar
 
Última edição:
TcpClient client = newTcpClient("localhost", 300);

localhost tem k tar entre aspas ou n?

se tiro dá-m erro de compilação se meto ao compilar fica cm essa linha amarela e com um erro a dizer
Nenhuma ligação pôde ser feita porque o computador de destino
as recusou activamente ::1:300
já depois da firewall perguntar se quero deixa-lo ligar a porta desejada, e eu meto sim
 
Última edição:
já vi como é k tao declaradas as estruturas, e já modifiquei, mas não encntro a struct do socklen_t

e tnho estes erros
Código:
Error 2 error C2011: 'sockaddr' : 'struct' type redefinition c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 22 winsocket
Error 3 error C2011: 'sockaddr_storage' : 'struct' type redefinition c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 59 winsocket
Error 4 error C2079: 'addr_size' uses undefined struct 'socklen_t' c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 90 winsocket
Error 7 error C2065: 'sockaddr' : undeclared identifier c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 116 winsocket
Error 8 error C2059: syntax error : ')' c:\users\hugo\desktop\c__webcam_161075762003[1]\webcam_test\winsocket\winsocket\winsocket.c 116 winsocket
 
Novo problema

Dps de ter consguido correr um programa k axei na net, consgo faze-lo correr no dev-c++ em c, e o programa em c# ta optimo.

com o compiador dev-c++ meto a libraria, tudo correcto e fica a funcionar a 5*, mas cmo sei k o dev n da pa colocar o comando "outportb()" kia faxe-lo em visual studio, mas está a dar m bastantes erros, mesm dps d temtar metr a msm .lib e tmb a wsock32.lib , e penso que seja de declarações k ele n conhece. Alguem me podia dar alguma dica?

Obg
 
Back
Topo