Re: newbie: socket api
Am Mittwoch, 26. Dezember 2012 23:02:08 UTC+1 schrieb Ian Collins:
Thomas Kaufmann wrote:
Hi there,
Please wrap your lines!
I use the socket-API. My Problem is:
I have a function (yes, a function not a method). And I want return
either the struct sockaddr_in or sockaddr_in6. How can do this? I
tried a void-pointer but there is an error-message.
What did you try? What error did you get?
--
Ian Collins
Here is my code:
#include "unp.h"
#include "init.h"
#include <exception>
void* InitAndConnect(int sockfd, int family, char *ip) {
// I want return this struct
struct sockaddr sa;
if (family == AF_INET) {
try {
struct sockaddr_in servaddr;;
bzero(&servaddr, sizeof(servaddr) );
servaddr.sin_family = family;
servaddr.sin_port = htons(SERV_PORT);
if (inet_pton(family, ip, &servaddr.sin_addr) <= 0) {
perror("inet_pton-error: ");
}
connect(sockfd, (SA*) &servaddr, sizeof(servaddr) );
// critical line
sa = servaddr;
} catch(std::exception& e) {
cout << e.what() << endl;
}
} else if (family == AF_INET6) {
struct sockaddr_in6 servaddr;
bzero(&servaddr, sizeof(servaddr) );
servaddr.sin6_family = AF_INET;
servaddr.sin6_port = htons(SERV_PORT);
inet_pton(family, ip, &servaddr.sin6_addr);
connect(sockfd, (SA*) &servaddr, sizeof(servaddr) );
// critical line
sa = servaddr;
}
// does' work
return sa;
}
int main(int argc, char *argv[]) {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
void* ptr = InitAndConnect(int sockfd, AF_INET, argv[1]) {
return 0;
}
Here are the errors:
xxx54@richard:~/myC++/unp/derplan> g++ -o init -Wall -pedantic -O3 init_tes=
t.cpp
init_test.cpp: In function =91void* InitAndConnect(int, int, char*)':
init_test.cpp:28:12: error: no match for =91operator=' in =91sa = ser=
vaddr'
/usr/include/bits/socket.h:179:3: note: candidate is: sockaddr& sockaddr::o=
perator=(const sockaddr&)
init_test.cpp:46:12: error: no match for =91operator=' in =91sa = ser=
vaddr'
/usr/include/bits/socket.h:179:3: note: candidate is: sockaddr& sockaddr::o=
perator=(const sockaddr&)
init_test.cpp:50:10: error: cannot convert =91sockaddr' to =91void*' in=
return
init_test.cpp: In function =91int main(int, char**)':
init_test.cpp:56:31: error: expected primary-expression before =91int'
init_test.cpp:56:61: error: expected =91,' or =91;' before =91{' toke=
n
init_test.cpp:55:7: warning: unused variable =91sockfd'
init_test.cpp:56:9: warning: unused variable =91ptr'
init_test.cpp:59:1: error: expected =91}' at end of input
init_test.cpp: In function =91void* InitAndConnect(int, int, char*)':
init_test.cpp:51:1: warning: control reaches end of non-void function
xxx54@richard:~/myC++/unp/derplan>