c - how to get client address in a multithreading TCP server for each connection -
in multithreading tcp server, don't know how store client address each cocnnection.
first, let's consider case in each thread, there 1 tcp connection(namely 1 connfd) @ same time.this client address used in each thread.
for multh-threading tcp server, there 3 types:
(1) 1 thread per connection, in type, can use thread-specific data store client address. like:
listen(listenfd, backlog); pthread_key_create(&key, null); for(;;){ connfd=accept(listenfd, client_addr, socklen); pthread_create(pid, null, func, null); .. }
and
func(){ pthread_setspecific(key,(void *)client_addr); // **and client_addr can obtained pthread_getspecific(key)** }
are there problem in solution? i'm afraid before pthread_setspecific()
called, accept()
called again , client_addr changed.
(2) half-syn , half-async: similar (1)
(3) leader-follower type:
connfd=listen(listenfd, backlog); pthread_key_create(&key, null); for(i:n){ pthread_create(pid, null, func, null); } func(){ accept(listenfd, client_addr, socklen); pthread_setspecific(key,(void *)client_addr); }
for type, still since client_addr may changed between accept() , pthread_setspecific().
for case each thread has many tcp connections @ same time, unimaginable!
so how can client address each thread? there work-around problem? thanks!
just call getpeername(2)
on socket in handling thread, no need fancy thread-local storage.
Comments
Post a Comment