text:
A simple TCP server
Write a program or function that listens for incoming TCP traffic on port N. It offers a simple service: it calculates sum of IP address fields of incoming connection and returns.
Program or function reads integer N from arguments or stdin. It listens to incoming TCP connections on port N. When someone connects to that port, the program calculates sum of its IP address fields and sends it back to the client with trailing newline and closes connection.

Port number N is a valid port, and 210 < N < 215
Trailing newline can be either \nor \r\n
You can use either IPv4 or IPv6. Since IPv6 addresses are written in hexadecimal form, you must also provide result in same format, for example 2001:0db8:0000:0042:0000:8a2e:0370:7334 => 12ecd.

This is code-golf. Standard rules and loopholes apply.
Example
You run your server with ./server 1234. The server is now running and waiting for connections on port 1234. Then a client from 127.0.0.1 connects to your server. Your server performs a simple calculation: 127+0+0+1 => 128 and sends the result to the client (with trailing newline): 128\n. Then server closes connection and waits for next client.
Leaderboard

var QUESTION_ID=76379,OVERRIDE_USER=20569;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Is it allowed to use inetd/xinetd or similar?

I like this, since it's a golfing challenge that golfing languages are unlikely to be very good at.

Not only is it amazing that a TCP server is apparently a very easy program to write, I am thoroughly floored at the fact that it's getting golfed for fun. I'll just go back to struggling with FizzBuzz like an imbecile.

@isaacg It's only time before someone finds the TCP server built-in in Mathematica

@MonkeyZeus To be fair, you will not see any good TCP server here. Making a reliable, scalable TCP server that handles all the intricacies of TCP (and your application protocol) well is a bit harder :D Though it certainly helps that the protocol is exceedingly simple - you don't even need to read the stream, something that I've seen broken in too many TCP servers to count :D

Bash + netcat + ss + …, 65 60 characters
nc -lp$1 -c'ss src :'$1'|awk \$0=\$5|tr .: +#|bc'
exec $0 $1

Not a serious solution, was just curious about this possibility.
Thanks to:

ninjalj for suggesting the awk based filtering (-5 characters)

Sample run:
(terminal 1)
bash-4.3$ ./ip-reduce.sh 8080

(terminal 2)
bash-4.3$ nc localhost 8080
128

bash-4.3$ telnet localhost 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
128
Connection closed by foreign host.

On Ubuntu you can get nc from netcat-traditional (no, netcat-openbsd is not good) and ss from iproute2.

Why do you say it isn't a serious solution? As long as it works as expected I see no reason why it shouldn't be considered serious. It's also the shortest by a pretty significant margin at the moment.

The biggest concern against it appeared during discussion with @JesseSielaff when I learned that on systems with configured IPv6, socket related information may be formatted differently. Have no such system to test it. For which I'm thinking whether would be more correct to turn it into CW.

My understanding of the spec is that you have to support IPv4 or IPv6, not both. So as long as it works for IPv4, not supporting IPv6 shouldn't matter, I would think.

@AlexA. At least I think my question says so. Should I clarify it?

@HannesKarppila, your question is clear. The possible issue is that my solution may require the operating system to be configured in a particular way to be able to run. So I'm worry because it may fail if IPv6 is configured, regardless whether I handle it or not. Someone who has IPv6 configured could tell it for sure…

-c'ss src :'$1'|awk \$0=\$5|tr .: +#|bc' instead of -c"ss src :$1|sed -z 's/.* \b//;y/.:/+#/'|bc" saves a few bytes.

What is the character cost of using ss if it has to be installed for this solution to work?

Nice way to discard ss's header line, @ninjalj. I also tried awk, but with "manual" header discarding, which made it longer. Thank you.

Linux ELF/x86, 146 bytes
00000000  7f 45 4c 46 01 00 00 00  5a 0e 00 00 5a 5e eb 10  |.ELF....Z...Z^..|
00000010  02 00 03 00 0c 50 eb 10  0c 50 eb 10 04 00 00 00  |.....P...P......|
00000020  5e 53 43 53 52 89 e1 b0  66 3d 20 00 01 00 cd 80  |^SCSR...f= .....|
00000030  97 55 6b ed 0a 01 c5 ac  2c 30 79 f6 43 0f cd 01  |.Uk.....,0y.C...|
00000040  dd 55 89 e1 6a 10 51 6a  10 51 57 89 e1 b0 66 cd  |.U..j.Qj.QW...f.|
00000050  80 43 43 b0 66 cd 80 01  64 24 08 89 e1 43 b0 66  |.CC.f...d$...C.f|
00000060  cd 80 89 c1 93 8d 74 24  1b 99 fd ac 01 c2 e2 fb  |......t$........|
00000070  89 f7 b0 0a aa 91 92 f6  f1 86 c4 04 30 aa 42 c1  |............0.B.|
00000080  e8 08 75 f3 42 89 f9 41  b0 04 cd 80 b0 06 cd 80  |..u.B..A........|
00000090  eb c9                                             |..|
00000092

Includes a 52-byte ELF header, a 32-byte program header, 111 bytes of program code + 3 bytes of code for skipping around inside the headers.
Information on how to create tiny ELF executables can be found at breadbox's "A Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux".
Linux/i386 uses the socketcall(2) multiplex system call, which takes in ebx the specific socket call (the SYS_* macros from /usr/include/linux/net.h), and in ecx a pointer to the argument area of the original library call.
Some things done to keep the executable small:

It assumes registers are zeroed on entry, which Linux does, but is not required by the ELF standard (the only requirement is that on entry EDX points to a finalization funtion (useful for executables loaded by the dynamic linker) or is NULL).
It assumes on launch (typically by a shell) the only open file descriptors are 0, 1, and 2. Which means that the listening socket will be fd 3, and the accepted socket will be fd 4.
It assumes there are exactly 2 arguments (including argv[0]).
The same stack space is reused for the calls to bind(2), listen(2) and accept(2).
To skip over the phentsize and phnum fields, a byte is prepended, turning into a CMP operation which takes the phentsize and phnum fields as an immediate (trick shamelessly stolen from breadbox's solution to 123 in anarchy golf).
x86 string operations LODS (load into accumulator and increment/decrement source index) and STOS (store from accumulator and increment/decrement destination index) are nice for short code.
XCHG EAX, reg is 1-byte, compared to MOV EAX, reg, which takes 2 bytes.
CDQ/CLTD (sign-extend EAX into EDX:EAX) can be used as a 1-byte way to zero the EDX register.
BSWAP is useful for implementing htons().

Nasm source:
BITS 32                                         ;
                                                ;   ELF HEADER    --   PROGRAM HEADER
; ELF HEADER                                    ; +-------------+
DB 0x7f,'E','L','F'                             ; | magic       |    +--------------------+
                                                ; |             |    |                    |
; PROGRAM HEADERS                               ; |             |    |                    |
DD 1                                            ; |*class   32b | -- | type: PT_LOAD      |
                                                ; |*data   none |    |                    |
                                                ; |*version   0 |    |                    |
                                                ; |*ABI    SysV |    |                    |
DD 0xe5a        ; offset = vaddr & (PAGE_SIZE-1); |*ABI vers    | -- | offset             |
                                                ; |             |    |                    |
entry:  pop     edx     ; edx = 2 (argc)        ; |*PADx7       | -- | vaddr = 0x10eb5e5a |
        pop     esi     ; discard argv[0]       ; |             |    |                    |
        jmp     short skip                      ; |             |    |                    |
DW 2                                            ; | ET_EXEC     | -- |*paddr LO           |
DW 3                                            ; | EM_386      | -- |*paddr HI           |
DD 0x10eb500c                                   ; |*version     | -- | filesz             |
DD 0x10eb500c                                   ; | entry point | -- | memsz              |
DD 4                                            ; | ph offset   | -- | flags: RX          |
                                                ; |             |    |                    |
skip:   pop     esi     ; esi = argv[1]         ; |*sh offset   | -- |*align              |
socket: push    ebx     ; default protocol (0)  ; |             |    |                    |
        inc     ebx                             ; |             |    |                    |
        push    ebx     ; SOCK_STREAM (1)       ; |             |    |                    |
        push    edx     ; AF_INET (2)           ; |*flags       |    +--------------------+
        mov     ecx, esp                        ; |             |
        mov     al, 0x66                        ; |*ehsize      |
DB 0x3d         ; cmp eax,0x10020               ; |             |
DW 32                                           ; | phentsize   |
DW 1                                            ; | phnum       |
                                                ; |             |
        int     0x80    ; socket(2, 1, 0)       ; |*shentsize   |
        xchg    edi, eax; edi = sockfd, eax = 0 ; |*shnum       |
        push    ebp     ; INADDR_ANY            ; |             |
                                                ; |             |
mult:   imul    ebp, 10 ; \_                    ; |*shstrndx    |
        add     ebp, eax; >                     ; |             |
        lodsb           ; >                     ; +-------------+
        sub     al,'0'  ; >
        jns     mult    ; / ebp = atoi(argv[1])                 ;       bind stack frame
                                                                ;    +-----------------------+
endmul: inc     ebx             ; SYS_BIND (2)                  ;    |        INADDR_ANY     |
                                                                ; +->| AF_INET | htons(port) |
        bswap   ebp                                             ; |  +-----------------------+
        add     ebp, ebx        ; AF_INET (2), htons(port)      ; |  |           16          |
        push    ebp                                             ; |  +-----------------------+
                                                                ; |  |         dummy         |
        mov     ecx, esp                                        ; |  +-----------------------+
        push    16              ; addrlen                       ; |  |           16          |
        push    ecx             ; dummy value                   ; |  +-----------------------+
        push    16              ; addrlen                       ; +--|          addr         |
        push    ecx             ; addr                          ;    +-----------------------+
        push    edi             ; sock                          ;    |         sockfd        |
        mov     ecx, esp                                        ;    +-----------------------+
        mov     al, 0x66
        int     0x80            ; bind(sockfd, addr, addrlen)
                                                                ;       accept stack frame
                                                                ;    +-----------------------+
listen: ;mov    byte [esp+8],1                                  ;    |        INADDR_ANY     |
        inc     ebx                                             ; +->| AF_INET | htons(port) |
        inc     ebx             ; SYS_LISTEN (4)                ; |  +-----------------------+
        mov     al, 0x66                                        ; |+>|           16          |
        int     0x80            ; listen(sockfd, backlog)       ; || +-----------------------+
                                                                ; || |         dummy         |
        add     [esp+8], esp                                    ; || +-----------------------+
accept: mov     ecx, esp                                        ; |+-|        &addrlen       |
        inc     ebx             ; SYS_ACCEPT (5)                ; |  +-----------------------+
        mov     al, 0x66                                        ; +--|          addr         |
        int     0x80            ; accept(sockfd, addr, &addrlen);    +-----------------------+
                                                                ;    |         sockfd        |
        mov     ecx, eax        ; ecx = 4                       ;    +-----------------------+
        xchg    ebx, eax        ; ebx = acceptfd, eax = 000000xx

        lea     esi, [esp+27]   ; point to the IP part of struct sockaddr_in
        cdq

        std                     ; reverse direction for string operations
addip:  lodsb                   ; \_
        add     edx, eax        ; > edx = sum of 4 IP bytes
        loop    addip           ; /

        mov     edi, esi        ; reuse struct sockaddr_in as scratch buffer
        mov     al, 10          ; '\n'
        stosb
        xchg    ecx, eax        ; ecx = 10
        xchg    eax, edx        ; edx = 0, eax = sum

divide: div     cl              ; \_
        xchg    al, ah          ; >
        add     al,0x30         ; >
        stosb                   ; > sprintf(scratch, "%d", sum)
        inc     edx             ; >
        shr     eax, 8          ; >
        jnz     divide          ; /

write:  inc     edx             ; ndigits + 1 ('\n')
        mov     ecx, edi
        inc     ecx
        mov     al,4
        int     0x80            ; write(acceptfd, scratch, scratchlen)
close:  mov     al, 6
        int     0x80            ; close(acceptfd)
        jmp     accept

This answer is way underappreciated.

C#, 284 283 282 278 274 254 bytes
class A{static int Main(string[]a){var b=new System.Net.Sockets.TcpListener(int.Parse(a[0]));b.Start();for(;;){var c=b.AcceptTcpClient();var d=c.Client.LocalEndPoint.Serialize();new System.IO.StreamWriter(c.GetStream()).WriteLine(d[4]+d[5]+d[6]+d[7]);}}}

Classic example of a basic C# TCP server. Testing:
Terminal 1:
$ ./Q76379.exe 1029

Terminal 2:
$ telnet localhost 1029
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
128
Connection closed by foreign host.

Firefox:

You can save 1 Byte by using int Main instead of void Main. As the program never returns the compiler doesn't require a return statement.

And no, it doesn't leak. It's actually pretty deterministic about releasing resources as well. Also, the argument to Start is optional, saving another character.

@Luaan Yeah, that was left over from debugging.

Also, you could use using on the TcpClient, which will save you three more characters (use the {} from the for), and doing the same with the StreamWriter should save one more.

@Luaan I need to explicitly Flush the StreamWriter to make it work properly.

Actually, you don't if you use using - Dispose calls Flush on a StreamWriter. The same goes for TcpClient - Dispose calls Close, among other things.

@Luaan Have you tested this?

It works for me, though in cases like this, I usually find the code more reliable since the buffering isn't entirely predictable. Note that it also closes the underlying network stream, so you can actually omit the using around the TcpClient as well, saving six or seven more characters, if I'm counting right :)

NodeJS, 146 134 127 bytes
require('http').createServer((q,s)=>s.end(eval(0+q.socket.remoteAddress.replace(/^.*:|\./g,'+'))+'\n')).listen(process.argv[2])

I finally get to post a NodeJS answer! IPv4 only right now.
Sample execution: node script.js 1024. From another terminal:
$ curl 127.0.0.1:1024
128

I count 127 bytes right now, although you can get it down to 126 by swapping out '\n' with a template string containing a literal newline.

Wouldn't this fail the requirements because your creating a HTTP server , I mean, it's technically a TCP server, but couldn't you just use the TCP module and save yourself a character?

Tcl, 92

1 byte saved thanks to @DonalFellows.

proc s {c a p} {puts $c [expr [string map .\ + $a]]
close $c}
socket -server s $argv
vwait f

Fairly self-explanatory:
socket -server s $argv creates a listening socket on the port specified in the arguments.
Every time a new connection arrives, the proc s is called, with channel, source-address and source-port as parameters.  string map substitutes . for + in the source address, and expr arithmetically evaluates the result, which is then puts back to the connection channel c.
vwait runs an event loop to catch the incoming connection events.

Credit to @DonalFellows for the following:
Here's a version that handles IPv6 (requires Tcl 8.6; most of the extra length is due to producing a hex response):
Tcl, 109
proc s {c a p} {puts $c [format %x [expr 0x[string map :\ +0x0 $a]]]
close $c}
socket -server s $argv
vwait f

Using apply doesn't seem to save anything. Nor can you use tcl::mathop::+ {*}[split $a .] as that's slightly longer. Nor can you shave anything from option names. But supporting IPv6 is pretty trivial to add, and only costs a few bytes of code more (and then a regsub-based approach is just as long).

ahhh, Tcl / Tcl-DP ... amazing bunch of tools. (in the '90s a professor showed us we could write a network-distributed Excel (with a grid, and including formulas evaluation!) shared among several persons with (iirc) 4 (short) lines for the server and 5 for the clients...

proc s {c a p} do you really need all that whitespace?

Groovy 133, 125, 93, 89
new ServerSocket(args[0]as int).accept{it<<(it.inetAddress.address as int[]).sum()+"\n"}

IPv4 only, probably.
Ungolfed:
new ServerSocket(args[0]as int).accept{
    it << (it.inetAddress.address as int[]).sum()+"\n"
}

Testing:
$ telnet localhost 9000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
128
Connection closed by foreign host.

.toInteger() → as int and s.inetAddress.address*.toInteger() → (s.inetAddress.address as int[]). And there is an extra space after .with.

@manatwork thx! Updated.

Python 3, 170 166 147 bytes
from socket import*
s=socket()
s.bind(("",int(input())))
s.listen()
while 1:
 c,a=s.accept()
 c.send(b"%d\n"%eval(a[0].replace(".","+"))),c.close()

Takes port on stdin, IPv4 only. Works on GNU/Linux (and, I assume, most other unices), which automatically expands "" to "0.0.0.0", not sure about Windows though.

You could save several bytes. Firstly, spaces in import * and , SOCK_STREAM are unnecessary. Also, the send line could be written more efficiently as c.send(b"%d\n"%eval(a[0].replace(".","+"))).

@HannesKarppila oh, thanks. forgot about the spaces, the eval hack is pretty cool though.

AF_INET and SOCK_STREAM are just constants; AF_INET is 2 and SOCK_STREAM is 1. Also, as mentioned, SOCK_STREAM is unnecessary; so you can shorten that by instead using s=socket(2).

can't you just do socket() and therefore save another byte?

Although unless i'm missing something, you need to pass something to s.listen()

@Foon as per help(socket.listen), "If not specified, a default reasonable value is chosen." (for the backlog parameter)

Ahh... python3 changed that behavior; good to know (re: socket.listen)

You could save another 3 chars by using semicolons to concatenate all the indented statements and slapping them right on the end of while 1:.

You can save 10 characters by using Python 2. Then, int(input()) becomes input() and the send part becomes c.send(`eval(a[0].replace(".","+"))`)

Do you need the close() call?  The challenge didn't say the code had to behave nicely. :)

Java, 371 368 350 344 333 310 295 282 bytes
Golfed
import java.net.*;class A{public static void main(String[]n)throws Exception{ServerSocket s=new ServerSocket(Integer.decode(n[0]));for(;;){try(Socket a=s.accept()){byte[]c=a.getInetAddress().getAddress();new java.io.PrintStream(a.getOutputStream()).println(c[0]+c[1]+c[2]+c[3]);}}}}

Ungolfed
import java.net.*;

class A {
    public static void main(String[] n) throws Exception {
        ServerSocket s = new ServerSocket(Integer.decode(n[0]));
        for (;;) {
            try (Socket a = s.accept()) {
                byte[] c = a.getInetAddress().getAddress();
                new java.io.PrintStream(a.getOutputStream()).println(c[0] + c[1] + c[2] + c[3]);
            }
        }
    }
}

Output
mallard@steamroller:~$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
128
Connection closed by foreign host.

Remove the int k= and replace the k with all the c things in Integer.toString(k). To save a few bytes.

You can also drop the space after your square brackets.

Change public class A to interface A and change Main from public static void to public void -- it's shorter and does the same thing

Thanks for the tips. @tac The main method has to be static :-(

Javas byte pretty sure messes up the return value for 192.168.2.1 or similar adresses with a byte above 127.

@MatthewSmith oh, then you can change it to static void for interface -- I don't know Java, just that interface allows dropping a keyword

Change interface to class should gain few more byte

Could also get rid of Integer.toString and use cast trick ((int)c[0] + c[1] + c[2] + c[3])

Actually it doesn't need a cast at all, it automagically gets turned into a string by the +'\n'.

Use a.getOutputStream().write((c[0] + c[1] + c[2] + c[3]+"\n").getBytes()); instead of new DataOutputStream(a.getOutputStream()).writeBytes(c[0] + c[1] + c[2] + c[3] + "\n")

I made a new Java solution that account for the byte overflow problem

Integer.valueOf is shorter than Integer.parseInt. Or Integer.decode for one less byte.

Isn't try(Socket a=...){} shorter than a.close();? Requires Java 7, but can gain bytes.

@ogregoire Yes, it's 5 bytes shorter now.

Now, after those changes, you can probably remove the braces after the for-loop to gain 2 extra bytes.

Use new java.io.DataOutputStream instead of importing it. Also, writeBytes(0+c[0]... for correctness.

Also, if you really want to use a class from java.io, use PrintStream::println, which is shorter and allows you in turn to remove the +"\n", but that doesn't beat Ortis' suggestion.

Hurrah, one byte shorter than C# now. Thanks @ogregoire

Replace Integer.valueOf with Short.valueOf.

PowerShell v2+, 303 268 257 227 bytes
nal n new-object;($l=n Net.Sockets.TcpListener($args[0])).Start()
for(){($w=n IO.StreamWriter(($c=$l.AcceptTcpClient()).GetStream())).Write((([Net.IPEndPoint]$c.Client.RemoteEndPoint).Address-replace"\.",'+'|iex))
$w.Dispose()}

Saved 35 bytes thanks to Matt ... Saved another 11 bytes by aliasing New-Object and minor tweaks ... Saved 30 more bytes by implicitly using localhost rather than any IP address and corrected to account for continual usage as originally specified and I missed
Really similar to the C# answer, since it's .NET underlying both. We save a few bytes here over the C# answer by being able to leverage the returning functionality of PowerShell (surrounding our declaration/assignment in parens, and then immediately calling the . methods), but we lose an awful lot by needing to formulate the summation. The fact that we've got slightly shorter class names/calls is really why this answer is beating C#.
Explanation
We first create a New-Alias (with the nal alias) to save on re-typing New-Object later. The rest of the first line is setting up a TCP Listener. We pass the command-line $args[0] as the input for creating a new System.Net.Sockets.TcpListener, stored as $l. That object is encapsulated in parens and immediately called with .Start() to have it actively open the socket.
Entering an infinite for loop, we then set our listener $l to blocking with AcceptTcpClient() which will wait for a connection. A reference to that connection (once it's made) is stored in $c, encapsulated in parens, and immediately called GetStream() to get the datastream. That datastream is passed to a new System.IO.StreamWriter constructor, $w, so we can manipulate it. That constructor is itself encapsulated in parens and immediately called Write(...).
Inside the Write(...) call, we take our client handle $c and obtain the client's RemoteEndPoint property. This is the only way (that I've found so far) to get the remote IP address. Next we need to re-cast that as a [System.Net.IPEndPoint] object so it's formatted correctly, encapsulate that in parens, and pull just the .Address property. We then -replace the literal periods with plus signs, then pipe it to Invoke-Expression (similar to eval) to obtain our summation.
After the IO write, we need to call .Dispose() to ensure the datastream is flushed to the client and closed. The TCP server drops the client connection without warning, so depending upon the client used it may hang for a while at this point. It then continues through the for loop without properly closing connections. This also means that it leaks memory and system handles like crazy, but we don't care about that, right? You may need to use Task Manager to kill the process when you're done running the server, though. :D
Also IPv4 only, as the summation barfs spectacularly trying to handle an IPv6 address, since : isn't a valid algebraic operator for iex to parse.

"Leaks memory and system handles like crazy" What, do you have to free() them after? delete[], maybe? :P

@tac Yeah, there's a whole slew of .close() and .dispose() methods we're not calling here that would cause people on Code Review to have a fit.

Oh, isn't PS GC'd? Or does the GC do refcounting and not scope-analysis?

@tac Yes, PowerShell does have garbage collection thanks to the underlying .NET system. But, depending on how you're calling or leveraging this script, you can run into bugs like this one leaking memory in the pipeline. The above code also isn't thread-safe, and so can run into GC issues with that, since we're not explicitly closing the socket.

In testing I could not get this to work, likely due to firewall issues that I don't feel like fixing so I cannot be sure but..... I think you can drop "System" from most if not all the type casts you have there ie: [Net.ipaddress]::Any works.

@Matt Indeed, thanks for that! I keep forgetting that the System can be implied.

@TimmyD, ive given you some competition :)

haha i love your turning the periods into plus signs and iexing it, maybe that's smaller than my measure

Go, 359 311
This is my first program in Go - It allowed to let me discover one thing : This is definitively not a good golfing language!
(Kudos to @steve who did most of the golfing !)
package main
import(n"net";t"strings";r"strconv";x"regexp";"os")
func main(){l,_:=n.Listen("tcp",":"+os.Args[1])
for{c,_:=l.Accept();var s int
for _,i:=range t.Split(x.MustCompile(":[0-9]+$").ReplaceAllLiteralString(c.RemoteAddr().String(),""),"."){
n,_:=r.Atoi(i);s=s+n};c.Write([]byte(r.Itoa(s)));c.Close()}}

But it sure is a nice language for making a tcp server!

Odd, am getting the result 360 when I connect from 192.168.0.67, rather than 427.

You could name the strings+strconv packages to save a few bytes.  e.g. "strings" becomes s "strings" so that the later strings.Split becomes just s.Split.

Hmm, can you not use ":4444" in net.Listen?

@Riking why not ?

@steve I fixed the problem regarding the incorrect sum, thx

This doesn't take the listening port as input.

Dont forget to drop the unnecessary fmt.Println(c.RemoteAddr().String()) line.  And to address the @TimmyD point, and avoid having to include 0.0.0.0, use l,_:=n.Listen("tcp",":"+os.Args[1])

...and after then combining a few lines should give you http://pastebin.com/tMAYn6Y3     Nice work on your first go golf....

Few more bytes shaved off http://pastebin.com/HY84sazE - starting to look a bit more "golfed" now

If you use import(."pkgname") all functions will be imported to the current namespace, you can then drop the prefix. eg. import ."fmt"; Println("foo")
If you use Sscanf from the fmt package to parse the address instead of regex it'll save you another few bytes, giving you the nice bonus of having Fprintln for returning the total instead of importing strconv.

Common Lisp, 110 bytes
(use-package'usocket)(lambda(p)(socket-server"localhost"p(lambda(u)(format u"~D~%"(reduce'+ *remote-host*)))))

Details
(use-package 'usocket)

(lambda (port)

  ;; create server with event-loop
  (socket-server "localhost"
                 port

                 ;; tcp-handler
                 (lambda (stream)
                   ;; format to stream to client
                   (format stream
                           "~D~%"
                           ;; add all elements of the host,
                           ;; a vector of 4 integers
                           (reduce #'+ *remote-host*))

                   ;; client connection is closed automatically
                   ;; when exiting this function
                 )))

Yay for Common Lithp!

PHP, 161 (56?)
This is my first post in here. I hope this goes right :)
<?php $s=socket_create_listen($argv[1]);while($c=socket_accept($s)){socket_getpeername($c,$r);socket_write($c,array_sum(explode('.',$r))."\n");socket_close($c);}

Ungolfed:
<?php
    $s = socket_create_listen($argv[1]); //Create socket
    while( $c = socket_accept($s) ) { // Loop accepting new connections
        socket_getpeername($c, $r); // Get IP address in $r
        socket_write($c, array_sum(explode('.', $r))."\n"); //Calculate sum
        socket_close($c); //Close connection and wait for next one
    }

Terminal:
$ php test.php 8080 &
$ telnet localhost 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
128
Connection closed by foreign host.

This only works for IPV4
Edit:
I just noticed that php supports basic server:
I decided stick to original character count unless somebody confirms if following is allowed :)
test2.php: (possible 56-byte solution)
<?=array_sum(explode('.',$_SERVER['REMOTE_ADDR']))."\n";

And then start service with:
php -S localhost:8080 test2.php

Chrome as client

Edit 2: wget as client
$ wget -qO- localhost:8080
128

I know rules say: "Program or function reads integer N from arguments or stdin", but is it ok if program in this case is php itself? Or is using builtin server in php considered loophole?

Welcome to Programming Puzzles & Code Golf! Your 161-byte solution looks great. Is the 56-byte solution you mentioned the one under test2.php? If so, I think you'd have to ask the OP whether they'd consider that kind of built-in acceptable for this challenge. It isn't a loophole though.

I would say, using a builtin TCP server would be acceptable, but in this case we talk about a builtin HTTP server. So the 56 byte solution 1) does nothing if the client only connects and sends nothing; 2) sends back only “[Wed Mar 30 10:15:02 2016] 127.0.0.1:47974 Invalid request (Malformed HTTP request)” without running test2.php in case the client sends for example “foo”; 3) sends full set of HTTP response headers before the actual required response in case the client sends valid HTTP request.

@Alex A. Thank you and yes, 56-byte solution is under test2.php :)

@manatwork You are correct but I was thinking that client is not clearly specified in this task. So is it ok to use browser or even more simplier something like "wget -qO- localhost:8080" as client?

@Mikael I think the 56-byte solution test2.php fails the basic description: "listens for incoming TCP traffic on port N," and requires an http client (wget or similar) not a simple TCP client (telnet or similar).

LiveScript, 107 105 bytes
(require \http)createServer(->&1.end((.reduce (+))<|it.connection.remoteAddress/\.))listen process.argv.0

Nothing much to add, it's just basic NodeJS stuff. Style points for &1 (second argument), <| (F# piping, akin to $ in Haskell) and biop: (+) in LS is like operator sections in Haskell: a curried binary function (that adds its operands).
Also a bit dirty: /, if given a literal string on its right, will do split.

q, 88 bytes
system raze"p ",1_.z.x;.z.pg:{(string sum"i"$0x0 vs .z.a),"\n"};.z.ph:{.h.hy[`;.z.pg[]]}

system raze"p ",1_.z.x: Takes the second command-line argument (the first "-" is for telling q not to interpret N as a script/file) and opens a port ("p ") with it.

Note: Calling q -p N sets the port as N automatically, but since the question seems to suggest that N should be an argument to the program rather than the executable itself, I've gone the longer way.

Inside the .z.pg function that handles incoming requests, .z.a holds the IP address as a 32-bit integer.

"i"$0x0 vs splits it into its integer 'constituents', and sum does the summation.
Last, string the numeric result and append "\n" to it to return to the client.

.z.ph is another function for HTTP GET requests, with extra handling to convert the string output into a valid HTTP response.

Demo - Server:
c:\q\w32>q - 1234
KDB+ 3.3 2015.11.03 Copyright (C) 1993-2015 Kx Systems
w32/ 4()core ... NONEXPIRE

Welcome to kdb+ 32bit edition
q)system raze"p ",1_.z.x;.z.pg:{(string sum"i"$0x0 vs .z.a),"\n"};.z.ph:{.h.hy[`;.z.pg[]]}
q)

Demo - Client (from another q session running on 127.0.0.1):
q)(hopen `::1234)""
"128\n"

Demo - Client (from curl):
$ curl localhost:1234
128

$

8086 machine code (16-bit DOS), 163 156 148 148 142 bytes
00000000  31 c0 bb 0a 00 31 c9 be  81 00 bf 80 00 8a 0d 01  |1....1..........|
00000010  cf 46 8a 0c 80 e9 30 f7  e3 00 c8 39 fe 72 f2 89  |.F....0....9.r..|
00000020  c3 89 c1 b8 01 10 ba ff  ff 31 f6 31 ff cd 61 53  |.........1.1..aS|
00000030  b8 00 12 bf 80 00 b9 01  00 ba ff ff cd 61 b8 00  |.............a..|
00000040  14 cd 61 31 c0 bb 0a 00  83 c7 06 8d 4d 04 26 02  |..a1........M.&.|
00000050  05 80 d4 00 47 39 cf 72  f5 bf 84 00 b9 80 00 bb  |....G9.r........|
00000060  0a 00 4f 31 d2 f7 f3 80  c2 30 88 15 39 cf 77 f2  |..O1.....0..9.w.|
00000070  1e 07 b8 0e 13 5b bf 80  00 b9 04 00 ba ff ff cd  |.....[..........|
00000080  61 b8 00 11 ba 01 00 cd  61 b8 00 4c cd 21        |a.......a..L.!|
0000008e

Equivalent assembly code:
org 0x100
tcp equ 0x61    ; NTCPDRV interrupt

    xor ax,ax
    mov bx,10
    xor cx,cx
    mov si,0x81     ; [ds:81]-[ds:FF] = command line args
    mov di,0x80     ; [ds:80] = strlen(args)
    mov cl,[di]
    add di,cx

@@: inc si
    mov cl,[si]     ; get character
    sub cl,'0'      ; convert char to int
    mul bx          ; ax *= 10
    add al,cl
    cmp si,di
    jb @b
    ; now ax = port number

    mov bx,ax       ; source port (leaving this 0 doesn't work?)
    mov cx,ax       ; dest port
    mov ax,0x1001   ; open TCP socket for listening
    mov dx,-1       ; infinite timeout
    xor si,si       ; any dest IP
    xor di,di
    int tcp
    ; ^ I think this call should block until a connection is established, but apparently it doesn't.

    push bx         ; bx = socket handle, save it for later

    mov ax,0x1200   ; read from socket
    mov di,0x80     ; es:di = buffer (just reuse argument area to save space)
    mov cx,1        ; one byte
    mov dx,-1
    int tcp         ; this will block until a client connects and sends one byte

    mov ax,0x1400   ; get TCP session status, bx=handle
    int tcp
    ; now es:di points to a struct containing the source/dest IP addresses and ports
    ; the docs say it's two dwords for each IP address, then two bytes for "ip_prot" and "active" (whatever that means)
    ; ...but actually each IP address is followed by the port number (one word)

    xor ax,ax
    mov bx,10
    add di,6        ; [es:di+6] = client IP
    lea cx,[di+4]
@@: add al,[es:di]  ; add all bytes together
    adc ah,0
    inc di
    cmp di,cx
    jb @b
    ; now ax contains the IP address sum

    mov di,0x84     ; recycle arguments area again
    mov cx,0x80
    mov bx,10
@@: dec di
    xor dx,dx
    div bx          ; dl = ax mod 10
    add dl,'0'      ; convert int to char
    mov [di],dl
    cmp di,cx
    ja @b
    ; now [ds:80]-[ds:83] contains an ascii representation of the IP address sum

    push ds
    pop es
    mov ax,0x130e   ; send data with newline, wait for ack
    pop bx          ; socket handle
    mov di,0x80     ; es:di = data
    mov cx,4        ; sizeof data
    mov dx,-1
    int tcp

    mov ax,0x1100   ; close TCP socket
    mov dx,1
    int tcp

    mov ax,0x4c00
    int 0x21

This assumes ntcpdrv is loaded at INT 0x61 (and any suitable packet driver at 0x60). Compile with fasm tcpserv.asm.
It has some issues though:

It doesn't check if the argument is a valid port number, or if it's even a number at all.
The client must send at least one byte, since I can't seem to find any other way to tell if a client has connected.
It only works once, and hangs on a second attempt. Works again after a reboot.
The returned value is left-padded with zeroes.
This is my very first code golf entry, and also my very first 8086 asm program. I'm sure there are ways to improve this further.

You can just post a hexdump of the compiled output for 148 bytes

Is that allowed? It would make this entry a bit more competitive...

If it's an executable program (on some system) that meets the spec, then yes! Binary-format golf is allowed, just not often seen because modern platforms have a lot of boilerplate for executable formats.

Alright, I've changed the entry to machine code. Also shaved a few more bytes off by using xor r,r instead of mov r,0.

Newlines are one byte, unless that code won't compile without \r\n newlines?

I wrote it on a dos machine where newlines are CR LF, so I just went with that. Either way it's kinda pointless to count the asm size now, might as well clean it up a bit and add some comments.

source port (leaving this 0 doesn't work?) On UNIX, giving a port of 0 lets the kernel randomly assign a port, then returns the new port number. I guess DOS doesn't have that functionality

That's supposed to happen here too, and it does work; int 0x61 returns a random local port in ax. But it also changes the listening IP to some garbage number (4.2.0.0 iirc)

Perl, 141 132 + 1 = 133 bytes
Golfed
$s=new IO::Socket::INET LocalPort=><>,Listen=>5,Reuse=>1;{$c=$s->accept;$_=$c->peerhost;y/./+/;$c->send(eval.$/);shutdown $c,1;redo}

Ungolfed
# listen on tcp port obtained from stdin
$s=new IO::Socket::INET(LocalPort=> <>,
                        Listen   => 5,
                        Reuse    => 1);

{
    # accept connection
    $c=$s->accept();

    # get the ip address
    $_=$c->peerhost();

    # replace dots with plus
    y/./+/;

    # send the evaluated version back, with a newline
    $c->send(eval . $/);

    # close
    shutdown($c,1);

    redo;
}

Example
$ echo 7777|perl -MIO::Socket::INET -e'$s=new IO::Socket::INET LocalPort=><>,Listen=>5,Reuse=>1;{$c=$s->accept;$_=$c->peerhost;y/./+/;$c->send(eval.$/);shutdown $c,1;redo}'

$ telnet 127.0.0.1 7777
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
128
Connection closed by foreign host.
$

Are you sure this is correct? I get the sum printed in the server's terminal, not the client's. Anyway, you can remove all parenthesis and change s/\./+/g → y/./+/.

Ahh, misread..will revise accordingly and incorporate your good y/ suggestion.

while(1){…} → {…;redo} according to user130144's great tip. And excepting the ->send() call, all other parenthesis are unnecessary.

NodeJS (ES6), 129 118 107 bytes
require('net').createServer(c=>c.end(eval(c.remoteAddress.replace(/\./g,'+'))+`
`)).listen(process.argv[2])

Works for IPv4. Run as node server.js <port>

Actually doesn't work if the server's using IPv6 (as, for instance, mine does automatically), since c.remoteAddress would then be ::ffff:127.0.0.1. (I tested on Node v5.9.1).

Also, you don't have a trailing newline, which should increase your score by 2 bytes.

@Frxstrem Whoops, forgot that newline. Only adds 1 byte though thanks to template strings. Regarding IP family: .listen() used to default to IPv4 first, but it seems either by bug or design that this has changed. The submission will still function properly on newer versions of node when IPv6 is disabled on the host machine.

Go, 211 bytes
package main
import(."fmt"
."net"
"os")
func main(){s,_:=Listen("tcp4",":"+os.Args[1])
for{c,_:=s.Accept()
var a,b,d,e int
Sscanf(Sprint(c.RemoteAddr()),"%d.%d.%d.%d",&a,&b,&d,&e)
Fprintln(c,a+b+d+e)
c.Close()}}

Can probably be golfed further, I'm not entirely satisfied with the way I have to parse the IP adress for instance, it looks like a horrible hack.
Listens on IPv4 on the port given as argument.

C, 535 bytes
Well, someone had to do this.
I added a single line break so the posted code actually has 536 characters.
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>
int main(int c,char**v){int f,l;char b[99];struct sockaddr_in d,e;f=socket(AF_INET,SOCK_STREAM,0);bzero(&d,sizeof(d));d.sin_family=AF_INET;d.sin_addr.s_addr=INADDR_ANY;d.sin_port=htons(atoi(v[1]));bind(f,&d, sizeof(d));listen(f,5);l=sizeof(e);
f=accept(f,&e,&l);bzero(b,99);int p,q,r,s;char g[INET_ADDRSTRLEN];inet_ntop(AF_INET,&(e.sin_addr),g,INET_ADDRSTRLEN);sscanf(g,"%d.%d.%d.%d",&p,&q,&r,&s);sprintf(b,"%d\n",p+q+r+s);write(f,b,strlen(b));return 0;}

compile with gcc [file_name] -o server
run with ./server [port]
connect with telnet localhost [port]

Nice answer! As mentioned before, you could save a few bytes by using actual values for some constants, such as AF_INET and SOCK_STREAM.

PowerShell, 208 206 192 152 bytes
($t=[net.sockets.tcplistener]$args[0]).start();for(){($z=$t.acceptsocket()).send([char[]]"$($z.remoteendpoint.address-replace"\.","+"|iex)");$z.close()}

version information:
Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.34209
BuildVersion                   6.3.9600.17400
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2

Thanks to TimmyD for saving me 14 bytes!
Massive thanks to TessellatingHeckler for saving me 40 bytes

@TimmyD ah oops I missed that that was necessary... fixed now

One of the ways programs are allowed to take input is from stdin. i suppose this particular question doesn't specify that as allowed but it's a general code-golf thing that i think should count for PowerShell. It's unfortunately different from bash in that it doesn't wait for input on stdin if none has been provided.

fair enough. fixed again

Alrighty, now for some golfs -- try the following at 192 -- ($t=new-object net.sockets.tcplistener($args[0])).start();for(){($z=$t.acceptsocket()).send(($x=[byte[]][char[]](""+($z.remoteendpoint.address-replace"\.","+"|iex))+32),$x.count,0);$z.close()}

damn didnt see that Send method with one argument, that changes everything!

feels like cheating taking your -replace "\.","+" but thanks

Oh wait no I read it wrong, it is just using the fact that assignment operations return their value. I never think to use that.

I think you can knock this down to 152 - drop new-object and cast directly, skip the byte array conversion and do a string cast differently, don't store $x at all and drop the remaining parameters to send(), and it becomes ($t=[net.sockets.tcplistener]$args[0]).start();for(){($z=$t.acceptsocket()).send([char[]]"$($z.remoteendpoint.address-replace"\.","+"|iex)");$z.close()} - which I've only tested quickly with netcat connecting, but it seems to work the same - connecting from localhost anyway.

Well that is interesting... I wonder how that type conversion works, does powershell automatically do that with constructors? I feel like ive tested that in the past and it didnt work. I'll take it though thanks

Python 2, 180 bytes
from SocketServer import*
TCPServer(('',input()),type('',(BaseRequestHandler,set),{'handle':lambda s:s.request.send(`eval(s.client_address[0].replace('.','+'))`)})).serve_forever()

Takes the port over stdin.

Mumps, 114 115 Bytes
Golfed:
R P F{S J=0,I="|TCP|1" O I:(:P) U I R K F K=1:1:4{S J=J+$P(##class(%SYSTEM.TCPDevice).PeerAddr(),".",K)} W J,! C I}

Ungolfed:
R P             ; Read Port # from STDIN ;
  F{            ; Loop over everything;
  S J=0,        ; Initial IP segment total
  I="|TCP|1"    ; TCP device
  O I:(:P)      ; Open the TCP device, port from input {and sticking a tongue out! :-) }
  U I           ; Use the TCP device
  R K           ; Read from STDIN (anything)
  F K=1:1:4{    ; Iterate 1->4 in variable K
    S J=J+      ; Accumulate the following segments of the IP in var. J
    $P(##class(%SYSTEM.TCPDevice).PeerAddr(),".",K) ; Grab each piece of IPv4.
            }   ; close the loop.
  W J,!         ; Write the total w/newline out the TCP port
  C I           ; close the TCP port to send.
}               ; end final loop

This is the InterSystems Caché version of Mumps - if there's a version out there that can acquire the TCP address shorter than ##class(%SYSTEM.TCPDevice).PeerAddr() (as it's almost a 1/3 of the entire program) it might have a better chance against some of the other languages posted already... ;-)
Edit: Thanks to @TimmyD - I missed the reading of the port from STDIN or arguments instead of being hardcoded. Edited; it added 1 byte to the program.

@TimmyD - Ah, you're correct. Missed that on reading through the requirements. Will edit posthaste.

Haskell, 216 bytes
Using the "network-simple" package (cabal install network-simple).  Needs a couple of language extensions (-XOverloadedStrings -XNoMonomorphismRestriction) to work.
import Network.Simple.TCP(serve)
import Network.Socket
import Data.Bits
main=getLine>>= \n->serve"*"n p
p(s,(SockAddrInet _ h))=()<$(send s$(show$sum$w h 24)++"\n")
m=255
w h 0=[h.&.m]
w h n=h`shiftR`n.&.m:(w h$n-8)

There are a couple of possible simplifications, including changing the w function to return the sum directly rather than a list, and using a function rather than a program so that the port number can be specified as an argument. I don't imagine this would reduce the size very much, though.  20 bytes perhaps?

Nice! Pretty sure you can still shave a few bytes off by renaming w to #, so w h n becomes h#n for a savings of 2 bytes per usage.

C, 243 188 bytes (or perhaps 217 162 bytes)
V2: see below for the explanations.
188 bytes:
s;main(g,v)char**v;{short S[8]={2,htons(atoi(v[1]))};char C[g=16];bind(s=socket(2,1,0),&S,g);for(listen(s,8);g=fdopen(accept(s,&C,&g),"w");fclose(g))fprintf(g,"%d\n",C[4]+C[5]+C[6]+C[7]);}

Slightly circumspect 162 bytes:
s;main(g){short S[8]={2,g};char C[g=16];bind(s=socket(2,1,0),&S,g);for(listen(s,8);g=fdopen(accept(s,&C,&g),"w");fclose(g))fprintf(g,"%d\n",C[4]+C[5]+C[6]+C[7]);}

Probably more golfing possible tomorrow morning. I'll tidy this post up after those updates.

V1:
This one was really quite fun to golf.
#include<netdb.h>
s,c,q;main(g,v)char**v;{struct sockaddr_in S={2,htons(atoi(v[1]))},C;bind(s=socket(2,1,0),&S,g=16);for(listen(s,8);c=accept(s,&C,&g);q=fclose(g)){for(g=4;g;q+=C.sin_addr.s_addr>>8*--g&255);fprintf(g=fdopen(c,"w"),"%d\n",q);}}

It works for IPv4. Mostly it's a straightforward implementation. The three main components are
Creating the socket:

struct sockaddr_in S={2,htons(atoi(v[1]))},C;bind(s=socket(2,1,0),&S,g=16);

We use the various explicit forms of the constants AF_INET etc, and make use of the fact that when a struct is initialised in C in this way the non-specified elements are set to zero.
Listen for clients, accept them, and close their connections:

for(listen(s,8);c=accept(s,&C,&g);q=fclose(g))

Finally to send each client the data:

for(g=4;g;q+=C.sin_addr.s_addr>>8*--g&255);fprintf(g=fdopen(c,"w"),"%d\n",q);

The IP is stored in C.sin_addr.s_addr as a 32 bit integer where each octet is represented by one of the four bytes. We sum these bytes with the for loop and then print them to the stream using fprintf.
I have a shorter 217 byte solution but I'm not entirely sure it doesn't violate the standard loopholes since it requires that the port is given in unary in network byte order as command line arguments. That is, to run the server on port 12345 one would need to call

$ ./tcp 1 1 1 1 ... 1 1 1

where the total number of 1s is 14640. To say the least it's a little... cumbersome. But here it is anyway:
#include<netdb.h>
s,c,q;main(g){struct sockaddr_in S={2,g},C;bind(s=socket(2,1,0),&S,g=16);for(listen(s,8);c=accept(s,&C,&g);q=fclose(g)){for(g=4;g;q+=C.sin_addr.s_addr>>8*--g&255);fprintf(g=fdopen(c,"w"),"%d\n",q);}}

Java, 283 275 bytes
Golfed
import java.net.*;class A{public static void main(String[] n)throws Exception{ServerSocket s=new ServerSocket(Integer.valueOf(n[0]));for(;;)try(Socket a=s.accept()){int v=0;for(byte b:a.getInetAddress().getAddress())v+=b&255;a.getOutputStream().write((v+"\n").getBytes());}}}

Ungolfed
import java.net.*;

class A {
public static void main(String[] n) throws Exception {
    ServerSocket s = new ServerSocket(Integer.valueOf(n[0]));
    for (;;)
        try (Socket a = s.accept()) {
            int v = 0;
            for (byte b : a.getInetAddress().getAddress())
                v += b & 255;
            a.getOutputStream().write((v + "\n").getBytes());
        }
}
}

Edit: Down to 274 thanks to @ogregoire

Much more elegant than mine.

Use 255 instead of 0xff. Otherwise, same remarks as Matthew's answer.

This isn't C. Java's main method is supposed to return void.

@dorukayhan indeed. Don't why I used int. Edited.

Java, 210 bytes
Golfed:
p->{java.net.ServerSocket x=new java.net.ServerSocket(p);for(;;){try(java.net.Socket s=x.accept()){byte[]b=s.getInetAddress().getAddress();s.getOutputStream().write((0+b[0]+b[1]+b[2]+b[3]+"\n").getBytes());}}};

Expanded:
@FunctionalInterface interface Consumer { // Define an interface that allows a function that throws an exception.
  void accept(int port) throws Exception;
}

Consumer consumer = (port) -> {
  java.net.ServerSocket serverSocket = new java.net.ServerSocket(port);
    for (;;) {
      try (java.net.Socket socket = serverSocket.accept()) {
        byte[] bytes = socket.getInetAddress().getAddress();
        socket.getOutputStream().write((0 + b[0] + b[1] + b[2] + b[3] + "\n").getBytes());
      }
    }
}

This a gathering of all the tips I gave in other Java answers, plus the writing as a function instead of a full program, which gains roughly 70 bytes compared to the program.

Haskell, 185 (+ 19 = 204)? bytes
import Network.Simple.TCP(serve)
import Network.Socket
import Data.List.Split
main=getLine>>=flip(serve"*4")(\(a,b)->()<$(send a$(++"\n")$show$sum.map read.take 4.sepByOneOf":."$show b)

Takes port number as one line on stdin; requires network-simple from Cabal.
As usual with Haskell answers that don't constrain themselves to pure functions, the imports take up far too many bytes. The trailing newline is also worth 9 bytes...
Somewhat similar to @Jules's answer, but I use string manipulation instead of byte operations. I stole used the -XOverloadedStrings extension as well, which is probably worth 19 bytes extra.

Lua, 169 162 160 153 151 148 138 129 bytes
Golfed version
m=require"socket".bind(0,...)::l::c=m:accept()f=0 for n in c:getpeername():gmatch"%d+"do f=f+n end c:send(f.."\n")c:close()goto l

It requires Luasocket to be installed and an interpreter that supports labels. I've tested it with Luajit and I can also confirm that the code does not work with Lua 5.1.
Ungolfed version
m=require"socket".bind(0,...)
::l::
c=m:accept()

f=0
for n in c:getpeername():gmatch"%d+" do
    f=f+n
end
c:send(f.."\n")

c:close()
goto l

Edit 1:
Changed i=({c:getpeername()})[1] to just i=c:getpeername()
Edit 2:
Removed braces from the require statement.
Edit 3:
Removed the braces around the vararg, decreased the byte count a little bit.
Edit 4:
Removed the parenthesis around "%d+", shorter by 2 bytes.
Edit 5:
Removed the unnecessary variable i.
Edit 6:
Changed the ip from "127.0.0.1" to 0. (Thanks to xyzzy on #lua)
Edit 7:
Removed the function call to tonumber since strings are cast to numbers automatically (Thanks to Trebuchette for the suggestion, I did not know this)

Only Lua 5.2 and up support labels, if you're curious

Also, Lua automatically casts strings to numbers with the + operator, so you can take out tonumber.

Haskell, 326 bytes
import Data.Bits
import Network.Socket
import System.IO
f n=withSocketsDo$do
 s<-socket AF_INET Stream defaultProtocol
 bind s$SockAddrInet n iNADDR_ANY
 listen s 1
 g s
g s=do
 (z,SockAddrInet _ a)<-accept s
 h<-socketToHandle z WriteMode
 hPutStrLn h$show$b a
 hClose h
 g s
b 0=0
b x=x.&.0xFF+b(x`shiftR`8)

Sadly I had to use Network.Socket to get access to the remote IP address as an integer rather than a string. It would have saved dozens of characters if I could just do s <- listenOn (PortNumber n), rather than having to explicitly call socket, bind and listen individually. But, sadly, Network.accept gives me a host string, not an IP address integer, so I had to resort to Network.Socket.accept and friends.
The function f takes a port number as argument, and creates a server socket (s) listening on that port. It then calls the function g with the server socket. g loops forever, accepting connections. The function b takes an actual IPv4 address and computes the sum of its digits.
I'm sure somebody somewhere can do this better than me. I wanted to show off just how damned easy socket stuff is in Haskell... but then failed miserably, because I need access to the IP address, which isn't usually easy to get.

The "network-simple" package provides a much nicer interface which passes the SockAddr to a function you give it, which makes things easier.  See my solution which I'm about to post...

A few simplifications are apparent: (1) I believe withSocketsDo is only necessary on Windows, so if running on Linux it can be ignored; (2) 0xFF is a character longer than 255; (3) converting the socket to a handle and using regular IO is a lot longer than using Network.Socket.send.  Yes, send is deprecated, but the reason is not relevant to this scenario (it only relates to non-ASCII text or binary data), so it seems reasonable to use it.

Network.accept gives me a host string, not an IP address integer Can't you just split the IP string on the ".", map Haskell's string-to-number function over the split string and sum the results?

Factor, 155 146 131 206 190 bytes
Well, I just learned a lot about low-level socket programming. I don't think I ever wanna do that again, because my thrhead hurts.
[ utf8 <threaded-server> readln 10 base> >>insecure [ remote-address get host>> "." split [ 10 base> ] map sum 10 >base print flush ] >>handler [ start-server ] in-thread start-server drop ]

Oh yeah, threaded, and doesn't return, right.

Can you use 10 base> instead of string>number?

@fedes. Wow, I never knew that existed. I think that will allow me to shorten a lot of my Factor answers!

And 10 >base for number>string, also.

@fedes. Those deserve an answer here :D

Racket, 265 bytes
#lang racket(define l(tcp-listen(string->number(read-line))))(let e()(define-values(i o)(tcp-accept l))(thread(λ()(define-values(a b)(tcp-addresses o))(write(~a(foldl + 0(map string->number(string-split a".")))o))(newline o)(close-output-port o)))(e)))

Ungolfed:
#lang racket
(define listener (tcp-listen (string->number (read-line))))
(define (mk-server)
  (let echo-server ()
    (define-values (in out) (tcp-accept listener))
    (thread
     (λ()
       (define-values (a b) (tcp-addresses out))
       (write (number->string (foldl + 0(map string->number(string-split a "."))) out))
       (write "\n" out)
       (close-output-port out)))
    (echo-server)))

Matlab, 128 139 Bytes
Listens on port n, Ipv4 only (even if it listens on IPv6 too).
function m(n);while 1;t=tcpip('0.0.0.0',n,'NetworkRole','server');fopen(t);fprintf(t,'%d\n',sum(sscanf(t.RemoteHost,'%d.')));fclose(t);end

This doesn't take the listening port as input.

k (55 characters)
This is essentially a translation of @h.j.k. solution in q with a couple of modifications.
."\\p ",*.z.x
.z.pg:{$+/0x0\:.z.a}
.z.ph:.h.hy[`].z.pg@

Usage: q filename.k PORT

AutoIT, 308 293 281 278 275 274 272 270 264 bytes
Func K($n)
TCPStartup()
$A=TCPListen("127.0.0.1",$n)
Do
$B=TCPAccept($A)
Until $B>0
While 1
$C=TCPRecv($B,$n)
If $C Then
$e=StringInStr($C,"st:")+4
$d=stringsplit(StringMid($C,$e,StringInStr($C,":")-$e),".")
ConsoleWrite($d[1]+$d[2]+$d[3]+$d[4])
EndIf
WEnd
EndFunc

Script-Example.com has an online compiler.
Reusing the port variable ($n) in the TCPRecv max-length parameter. Since it is never going to be less than 1024, it's saving me a byte.

Rust, 185 bytes
use std::{io::*,net::*};|a|while let Ok((mut a,SocketAddr::V6(b)))=TcpListener::bind(("::",a)).unwrap().accept(){write!(a,"{:x}
",b.ip().segments().map(|a|a as _).iter().sum::<u32>());}

This is a closure of type fn(u16). It accepts IPv6 connections and formats its output in hexadecimal. Golfing in Rust can be pretty challenging due to the number of transformations allowed by the compiler. Rust 1.55.0 or higher is necessary to compile this program.

LispyScript, 196 bytes
(->(require"http")(.createServer(function(q r)(r.end((str(-> (r.socket.remoteAddress)(.split".")(.map parseFloat)(.reduce (function(x y)(+ x y)))))'\n')(.listen(get 2 process.argv)"127.0.0.1"))))

If it looks like one of the Node submissions above, that's because it's pretty much just Node with  a prettier face.
Ungolfed:
(->
  (require "http")
  (.createServer
    (function (request response)
      (response.writeHead 200 {'Content-Type': 'text/plain'})
      (response.end
        (str (-> (request.socket.remoteAddress)
             (.split ".")
             (.map parseFloat)
             (.reduce (function (x y) (+ x y)))))
          '\n')
  (.listen (|| (get 2 process.argv) 1337) "127.0.0.1"))))

Two functions, two method chains.

NodeJS, (IPv4 and IPv6) 105 Bytes
require("net").createServer(s=>s.end(eval(s.remoteAddress.replace(/[:.]/g,"+"))).listen(process.argv[2])

Explanation:
require("net")               # TCP library
 .createServer(              # Create the server
   s=>                       # Socket is s
    s.end(                   # Print and end the connection
     eval(                   # Treat the following string like JavaScript
      s.remoteAddress        # The IP address (IPv4 or IPv6, depending on connection)
       .replace(/.|:/g, "+") # Replace all . and : with +
 )))                         # Close server response
 .listen(process.argv[2])    # Listen on the third index of the arg array (["node", "filename.js", "first arg"])

There is a missing parenthesis in the original code (not in the explanation)

Object Pascal, 342 340 bytes
A small (well the pascal definition of small...) server with the lowest level Sockets library. Listenes to IP4, port no. on the commandline.
uses sockets;var s,c,l,i,f:integer;a,b:TInetSockAddr;g:string;begin val(ParamStr(1),f,i);s:=fpSocket(2,1,0);a.sin_family:=2;a.sin_port:=ntobe(f);l:=sizeof(a);fpBind(s,@a,l);repeat fpListen(s,1);c:=fpaccept(s,@b,@l);f:=0;for i:=1to 4do f:=f+b.sin_addr.s_bytes[i];Str(f,g);g:=g+#10;fpsend(c,@g[1],length(g),0);fpshutdown(c,2);until False;end.

Ungolfed:
uses
  sockets;
var
  s, c, l, i, f: integer;
  a, b: TInetSockAddr;        { a=server, b=client }
  g: string;
begin
  val(ParamStr(1), f, i);     { store port no. in f }
  s := fpSocket(2, 1, 0);     { 2=AF_INET, 1=SOCK_STREAM, 0=PF_UNSPEC }
  a.sin_family := 2;          { 2=AF_INET }
  a.sin_port := ntobe(f);     { port to listen to, address initialized to localhost by default }
  l := sizeof(a);
  fpBind(s, @a, l);           { bind socket to address:port }
  repeat
    fpListen(s ,1);           { listen for one incoming connection }
    c := fpaccept(s, @b, @l); { accept connection, client address in b }
    f := 0;
    for i:=1 to 4 do
      f := f+b.sin_addr.s_bytes[i]; { add 4 bytes of client address }
    Str(f, g);                      { store f in a string }
    g := g+#10;                     { add newline }
    fpsend(c, @g[1], length(g), 0); { send the addition result }
    fpshutdown(c, 2);               { close the connection }
  until False;
end.

Common LIsp (Lispworks), 564 bytes
(require "comm")(defun make-stream-and-talk(handle)(let((stream(make-instance 'comm:socket-stream :socket handle :direction :io :element-type 'base-char)))(mp:process-run-function(format nil "" handle) '() 'f stream)))(defun f(stream)(unwind-protect(progn(multiple-value-bind(address port)(comm:socket-stream-address stream)(declare(ignore port))(format stream "~S"(reduce #'+(mapcar #'parse-integer(split-sequence "."(comm:ip-address-string address)))))(force-output stream))(close stream))))(comm:start-up-server :function 'make-stream-and-talk :service 10246)

ungolfed:
    (require "comm")
    (defun make-stream-and-talk (handle)
      (let ((stream (make-instance 'comm:socket-stream
                                   :socket handle
                                   :direction :io
                                   :element-type
                                   'base-char)))
        (mp:process-run-function (format nil ""
                                         handle)
                                 '()
                                 'f stream)))

    (defun f (stream)
      (unwind-protect
          (progn
            (multiple-value-bind (address port)
                (comm:socket-stream-address stream)
              (declare (ignore port))
              (format stream "~S"
                      (reduce #'+
                              (mapcar #'parse-integer
                                      (split-sequence "."
                                                      (comm:ip-address-string address)))))
              (force-output stream))
            (close stream))))

    (comm:start-up-server :function 'make-stream-and-talk
                          :service 10246)

Usange:
    c:\~]$ telnet 127.0.0.1 10246

    Connecting to 127.0.0.1:10246...
    Connection established.
    To escape to local shell, press 'Ctrl+Alt+]'.
    you sent: 128
    Connection closed by foreign host.

    Disconnected from remote host(127.0.0.1:10246) at 23:42:56.

    Type `help' to learn how to use Xshell prompt.

Note:
reference Lispworks documents

Racket, 174 bytes
(do([l(tcp-listen 1234)])(#f)(let*-values([(i o)(tcp-accept l)][(a b)(tcp-addresses i)])(displayln(for/sum([s(string-split b".")])(string->number s))o)(close-output-port o)))

Ungolfed
(do ([l (tcp-listen 1234)])
    (#f)
  (let*-values ([(i o) (tcp-accept l)]
                [(a b) (tcp-addresses i)])
    (displayln
     (for/sum ([s (string-split b ".")])
       (string->number s))
     o)
    (close-output-port o)))

Shoutout to cat for bringing the Racket competition!


text:
Wargame Tank Simulation
Some of you may have heard of the Wargame series of computer based real time strategy game.  These games pit teams of players with primarily cold war era units to see how a hot cold war would have played out.  The goal of this challenge is to simulate a tank battle in these games.
Input

Two "tanks" (one red and one blue) will be entered into your program or function.  Each tank is classified by a rate of fire, accuracy, armor value, and attack power value.

Challenge
From the inputs above, simulate the two tanks fighting.  You will do this by having each tank fire according to its rate of fire.  If it hits (randomly determined by accuracy), a tank will do damage according to the armor value of its target and its own attack power.  The formula for damage is floor[(attackpower - armor)/2].  Therefore a tank with 10 attack power against a tank with 5 armor would do 2 damage.
Tank crews also have morale, which follows the following rule

There are four possible morale values; calm, worried, scared, and panicked. Tanks always start calm.  These names do not need to be in your code, in the sample below I've used calm = 1, worried = 2, etc.
Each morale value reduces the accuracy as follows: Calm -> 100% (no change), worried -> 75%, scared -> 50%, panicked -> 25%.   Therefore a panicked tank which normally has 60% accuracy now has 0.25 * 0.6 = 15% accuracy
Each hit by the opposing tank degrades morale by one level, each miss upgrades the morale by one level.

For example:
morale: calm  |  worried  |  calm  |  worried  |  scared
hit:         hit         miss     hit         hit

Rules:

Input should be two parameters to repesent each tank (I've used two tuples in the example below). Inputs may be provided in any order, just be sure to state which one is which. Input may be provided by user input via STDIN, read from a file, or parameters passed to a function call.
Each tank starts with 10 health.
Rate of fire will either be 8.5, 7.5, 6.5, 6, 5, or 3 seconds between shots.
Tanks start loaded, so each fires at time = 0.  Because Communists are sneaky, red fires first.
Accuracy must be randomly rolled.
Ineffective hits (hits which do no damage) have an effect on morale! (because it probably sounds terrifying)
Naturally since we want to see the action, output will be an update after each shot.  The update will contain the time of the shot, whom it was made by (red or blue), health of both tanks, and the morale of both tank crews.  Output maybe be presented in any format so long as it contains all of the required information in a human readable fashion (items must be delimited in some way).  Similar to input, please describe your output format in the answer.
Engagements are limited to 100 seconds. If you play the game you know this is because a plane has swooped in by then.  For our purposes if both tanks are alive at this point, it is a draw.
After one tank reaches 0 health (or after 100 seconds), print which tank is victorious ("Red" or "Blue") or "Draw" if appropriate.  I don't care about  trailing whitespace or newlines.
Printing output may be printing to STDOUT or writing to a file
Shortest answer in bytes wins

Sample Python Implementation
This is a little sample I worked up to demonstrate some of the methodology.  It takes the two tanks as tuples to the main() function, then outputs a nice little table.  Your output does not need to be so fancy.  For the curious, it's 1,930 bytes.  You can do better.
Sample Tanks:
Some tanks to use for you, the numbers are ROF, accuracy, armor, and power.

T-72A: 8.5, 45%, 12, 16
T-72BU: 8.5, 55%, 22, 23
T-80: 7.5, 40%, 14, 16
T-80U: 7.5, 60%, 20, 23
M1 Abrams: 7.5, 55%, 16, 18
M1A2 Abrams: 7.5, 60%, 22, 24
Leclerc: 6, 65%, 20, 20
STRV-103D: 5, 60%, 18, 16
Zhalo (I know, not a tank): 3, 60%, 2, 18

How do half second rates of fire work?

It's not really rate of fire, but time in between shots.  So 8.5 corresponds to about 7 rounds per minute

Right, but each round is a second right? Should a tank with 8.5 fire on 0, 9, 17, 25, etc?

Nice new name.  But no, they fire on exact values, so 0, 8.5, 17, etc.  Check out the sample output in the python reference case

So is each round half a second?

I am not sure what you are asking.  The rounds are fired at intervals defined by the input.  The shot doesn't take any time.

Each round of combat. Eg, at second 0, both tanks fire. Does it then advance to second 1 or second 0.5?

I see what you're getting at now.  In the sample implementation, I pre-computed all of the shot times.  You could simulate actual time step however as you are suggesting.  In this case you are free to select whatever time step you want, so long as you don't miss any shots

This would be cooler as a [tag:koth] challenge.

Python 3, 465
Saved 8 bytes thanks to wnnmaw.
Saved 34 bytes thanks to DSM.
Expects tanks as lists as follows, [Rate of Fire, Accuracy, Armor, Attack]
from random import*
def f(r,b):
 r+=10,1;b+=10,1
 for x in range(200):
  if r[4]<1:return"Blue"
  if b[4]<1:return"Red"
  if x%int(r[0]*2)<1:
   if random()>=(r[1]*r[5]):b[4]-=(r[3]-b[2])//2;b[5]-=(b[5]!=0.25)/4
   else:b[5]+=(b[5]<1)/4
   print('r,%f,%d,%f,%d,%f'%(x/2,*r[4:],*b[4:]))
  if x%int(b[0]*2)<1:
   if random()>=(b[1]*b[5]):r[4]-=(b[3]-r[2])//2;r[5]-=(r[5]!=0.25)/4
   else:r[5]+=(r[5]<1)/4
   print('b,%f,%d,%f,%d,%f'%(x/2,*r[4:],*b[4:]))
 return"Draw"

Prints the output as Attacker,TimeOfShot,RedHealth,RedMorale,BlueHealth,BlueMorale. Morale is represented as a float.

You can save 9 bytes with from random import*

If you use Python 2 you can save some bytes by using tabs as 2nd and 3rrd intendation level. It might also be worth it to get the input via input() and not using a function. This way you get rid of one intendation level.

@DenkerAffe I'd lose the ability to splat in the format string (plus I don't have 2 installed).

You can save some by changing instances of 0.25 to 1/4, since this is Python 3.

You could probably save some bytes by moving the ¼ factor into the random calculation.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Who's the king of the tournament?
Background
Consider a round-robin tournament, in which each contestant plays one game against every other contestant.
There are no draws, so every game has a winner and a loser.
A contestant A is a king of the tournament, if for every other contestant B, either A beat B, or A beat another contestant C who in turn beat B.
It can be shown that every tournament has at least one king (although there may be several).
In this challenge, your task is to find the kings of a given tournament.
Input and output
Your input is an N × N boolean matrix T, and optionally the number N ≥ 2 of contestants.
Each entry T[i][j] represents the outcome of the game between contestants i and j, with value 1 representing a win for i and 0 a win for j.
Note that T[i][j] == 1-T[j][i] if i != j.
The diagonal of T consists of 0s.
Your output shall be the list of kings in the tournament that T represents, using either 0-based or 1-based indexing.
The order of the kings is irrelevant, but there should not be duplicates.
Both input and output can be taken in any reasonable format.
Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Test cases
These test cases use 0-based indexing.
For 1-based indexing, increment each output value.
 2 [[0,0],[1,0]] -> [1]
 3 [[0,1,0],[0,0,0],[1,1,0]] -> [2]
 3 [[0,1,0],[0,0,1],[1,0,0]] -> [0,1,2]
 4 [[0,1,1,1],[0,0,1,0],[0,0,0,0],[0,1,1,0]] -> [0]
 4 [[0,1,1,0],[0,0,1,0],[0,0,0,1],[1,1,0,0]] -> [0,2,3]
 5 [[0,1,0,0,1],[0,0,0,0,1],[1,1,0,0,0],[1,1,1,0,1],[0,0,1,0,0]] -> [3]
 5 [[0,1,0,1,0],[0,0,1,1,1],[1,0,0,0,0],[0,0,1,0,1],[1,0,1,0,0]] -> [0,1,4]
 5 [[0,0,0,0,0],[1,0,1,1,0],[1,0,0,0,1],[1,0,1,0,1],[1,1,0,0,0]] -> [1,3,4]
 6 [[0,0,0,0,0,0],[1,0,1,1,0,0],[1,0,0,1,1,0],[1,0,0,0,1,1],[1,1,0,0,0,1],[1,1,1,0,0,0]] -> [1,2,3,4,5]
 6 [[0,0,1,1,1,0],[1,0,0,1,1,1],[0,1,0,0,1,0],[0,0,1,0,0,1],[0,0,0,1,0,1],[1,0,1,0,0,0]] -> [0,1,2,3,5]
 6 [[0,1,1,0,0,1],[0,0,0,1,0,1],[0,1,0,1,1,0],[1,0,0,0,1,1],[1,1,0,0,0,0],[0,0,1,0,1,0]] -> [0,1,2,3,4,5]
 8 [[0,0,1,1,0,1,1,1],[1,0,1,0,1,1,0,0],[0,0,0,1,1,0,0,0],[0,1,0,0,0,1,0,0],[1,0,0,1,0,1,0,0],[0,0,1,0,0,0,1,0],[0,1,1,1,1,0,0,1],[0,1,1,1,1,1,0,0]] -> [0,1,4,6,7]
20 [[0,0,1,1,0,1,1,0,0,0,0,1,1,0,1,1,1,1,0,1],[1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1],[0,0,0,1,0,0,0,1,1,0,1,0,1,0,0,0,0,0,1,1],[0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,0,0,1,1,1],[1,0,1,0,0,0,0,1,1,0,1,1,1,0,1,1,1,1,0,1],[0,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,1,1,0,1],[0,0,1,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,1,0],[1,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,1,1,1,0],[1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,1],[1,0,1,0,1,0,1,1,0,0,1,0,0,0,0,1,0,1,1,1],[1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,0],[0,1,1,0,0,1,1,0,0,1,0,0,1,1,1,1,1,0,1,1],[0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,1],[1,0,1,1,1,0,0,0,0,1,0,0,1,0,1,1,1,1,1,1],[0,0,1,0,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1],[0,0,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,1,1],[0,0,1,1,0,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1],[0,0,1,0,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1],[1,0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,1,0]] -> [0,1,3,4,5,7,8,11,15,17,18]

(Are there any run time or memory limits?) Nevermind. I completely misunderstood the spec.

@Dennis Nope. As long as your program would theoretically work given unlimited time and memory, you're fine.

Just to clarify: T[a][b] is the same match as T[b][a] but viewed from opposite angle, so T[a][b] == !T[b][a]

@edc65 That's a good observation. I edited it into the challenge.

Matlab, 36 35 29 bytes
@(T,N)find(sum(T*T>-T,2)>N-2)

Let us find out if i is a king. Then for each j the value T[i][j]==1 OR there is a k such that T[i][k] * T[k][l] == 1. But the second condition can also be replaced by sum_over_k(T[i][k] * T[k][l])>0, but this is just an entry of the matrix T*T (if you consider T as a matrix). The OR can then be replayed by adding T to that result, so we just have to check if n-1 values of the row i of T*T+T are greater than zero, to see whether i is king. This is exactly what my function does.
(This is MATLAB, so the indices are 1-based.)
The MATLAB matrices should be encoded with semicolons as line delimiters:
[[0,0,0,0,0];[1,0,1,1,0];[1,0,0,0,1];[1,0,1,0,1];[1,1,0,0,0]]

You can probably save a few bytes taking the number of contestants as input, instead of doing size(T,1)

Jelly, 13 12 11 bytes
a"€¹o/€oḅ1M

Output is 1-based. Try it online!
Alternatively, using bitwise operators instead of array manipulation:
×Ḅ|/€|ḄBS€M

Again, output is 1-based. Try it online!
Background
For contestant A, we can find all B such that A beat C beat B by taking all rows that correspond to a C such that C beat A. Ifr the Bth entry of the Cth is 1, we have that C beat B.
If we compute the logical ORs of all corresponding entries of the selected columns, we get a a single vector indicating whether A beat B by transitivity or not. Finally, ORing the resulting vector with the corresponding row of the input matrix gives Booleans whether A beat B, either by transitivity or directly.
Repeating this for every row, we count the number of 1's in each vector, therefore computing the amount of contestants each A beat. Maximal counts correspond to kings of the tournament.
How it works
a"€¹o/€oḅ1M  Main link. Argument: M (matrix)

   ¹         Yield M.
  €          For each row of M:
a"           Take the logical AND of each entry of that row and the corr. row of M.
    o/€      Reduce each resulting matrix by logical OR.
       o     Take the logical OR of the entries of the resulting maxtrix and the
             corr. entries of M.
        ḅ1   Convert each row from base 1 to integer, i.e. sum its elements.
          M  Get all indices of maximal sums.

×Ḅ|/€|ḄBS€M  Main link. Argument: M (matrix)

 Ḅ           Convert each row of M from base 2 to integer. Result: R
×            Multiply the entries of each column of M by the corr. integer.
  |/€        Reduce each row fo the resulting matrix by bitwise OR.
     |Ḅ      Bitwise OR the results with R.
       BS€   Convert to binary and reduce by sum.
             This counts the number of set bits for each integer.
          M  Get all indices of maximal popcounts.

You know, people keep posting these and saying x "bytes", but is "ḅ" really encoded in 1 byte in any standard encoding?  Sorry, but I find these hyper-condensed stack-based languages completely uninteresting because it feels like cheating to just assign every conceivable function to a unicode character.

@MattPutnam Jelly uses its own custom encoding. (Also it isn't stack-based)

@MattPutnam I've had similar sentiments, but they don't detract at all from traditional golfing. No one looks down on the traditional languages just because these exist, and unlike other SE sites, this doesn't exactly have the 'this answer is obvjectively better than that answer'. Also, while technically not disallowed, they don't alter the language to support a question (although they may, after the fact, realize a useful shortcut for future questions and make that an operation).

Why do these algorithms output the kings?

@Dennis I see now, its basically Boolean matrix multiplication done via logic or bit arithmetic. Actual matrix multiplication wouldn't be shorter?

@xnor It probably would, but it's not implemented yet...

JavaScript (ES6), 83 bytes
a=>a.map((b,i)=>b.every((c,j)=>c|i==j|b.some((d,k)=>d&a[k][j]))&&r.push(i),r=[])&&r

You can save 1 with
a=>a.map((b,i)=>b.every((c,j)=>c|i==j|b.some((d,k)=>d&a[k][j]))&&i+1).filter(a=>a)
but it means you have to output 1-indexed which is a serious bummer

Python using numpy, 54 bytes
import numpy
lambda M:(M**0+M+M*M).all(1).nonzero()[0]

Takes in a numpy matrix, outputs a numpy row matrix of 0-based indices.
Another way to think of a king is as a contestant for which all contestants are in the union of the king, the people the king beat, and the people those people beat. In other words, for every contestant, there is a path of length at most 2 from the king to them among the "beat" relation.
The matrix I + M + M*M encodes the numbers of paths of 0, 1, or 2 steps from each source to each target. A player is a king if their row of this matrix has only positive entries. Since 0 is Falsey, all tells us if a row is all nonzero. We apply this to each row and output the indices of the nonzero results.

Looks exactly like my approach but with a differnt interpretation, interesting=)

MATL, 12 10 9 bytes
Xy+HY^!Af

Input is: first the number of contestants, and on a separate line a matrix with rows separated by semicolons. Output is 1-based.
For example, the fifth test case has input
4
[0,1,1,0; 0,0,1,0; 0,0,0,1; 1,1,0,0]

and the last test case has input
20
[0,0,1,1,0,1,1,0,0,0,0,1,1,0,1,1,1,1,0,1; 1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1; 0,0,0,1,0,0,0,1,1,0,1,0,1,0,0,0,0,0,1,1; 0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,0,0,1,1,1; 1,0,1,0,0,0,0,1,1,0,1,1,1,0,1,1,1,1,0,1; 0,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,1,1,0,1; 0,0,1,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,1,0; 1,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,1,1,1,0; 1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,1; 1,0,1,0,1,0,1,1,0,0,1,0,0,0,0,1,0,1,1,1; 1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,0; 0,1,1,0,0,1,1,0,0,1,0,0,1,1,1,1,1,0,1,1; 0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,1; 1,0,1,1,1,0,0,0,0,1,0,0,1,0,1,1,1,1,1,1; 0,0,1,0,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1; 0,0,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,1,1; 0,0,1,1,0,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1; 0,0,1,0,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1; 1,0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0; 0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,1,0]

Try it online!
Explanation
Xy    % Implicitly take input: number. Push identity matrix with that size
+     % Implicitly take input: matrix. Add to identity matrix
HY^   % Matrix square
!     % Transpose
A     % Row vector with true entries for columns that contain all nonzero values
f     % Indices of nonzero values

MATL < Jelly \m/

Javascript 136 131 121 112 bytes
(n,m)=>m.map((a,k)=>eval(a.map((o,i)=>o||eval(a.map((p,j)=>p&&m[j][i]).join`|`)).join`+`)>n-2&&k+1).filter(a=>a)

Call using:
f=(n,m)=>m.map((a,k)=>eval(a.map((o,i)=>o||eval(a.map((p,j)=>p&&m[j][i]).join`|`)).join`+`)>n-2&&k+1).filter(a=>a)

f(20,[[0,0,1,1,0,1,1,0,0,0,0,1,1,0,1,1,1,1,0,1],
     [1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1],
     [0,0,0,1,0,0,0,1,1,0,1,0,1,0,0,0,0,0,1,1],
     [0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,0,0,1,1,1],
     [1,0,1,0,0,0,0,1,1,0,1,1,1,0,1,1,1,1,0,1],
     [0,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,1,1,0,1],
     [0,0,1,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,1,0],
     [1,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,1,1,1,0],
     [1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,1],
     [1,0,1,0,1,0,1,1,0,0,1,0,0,0,0,1,0,1,1,1],
     [1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,0],
     [0,1,1,0,0,1,1,0,0,1,0,0,1,1,1,1,1,0,1,1],
     [0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,1],
     [1,0,1,1,1,0,0,0,0,1,0,0,1,0,1,1,1,1,1,1],
     [0,0,1,0,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1],
     [0,0,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,1,1],
     [0,0,1,1,0,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1],
     [0,0,1,0,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1],
     [1,0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0],
     [0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,1,0]])

watchout because output is 1-indexed (saved a few bytes not trying to filter out 0s vs falses)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Toy store profits
The story
"2016? Al..right," grumbled toy seller Hilbert. He opened his eyes, wiped salad dressing trickling out of his ear and ate a morning kick-start cremeschnitte. Exemplar holidays. He needs to go to work now though, and finish the year's accounting.
Christmas is a very yielding period of the year, especially for his sales. Hilbert knows exactly how it works: A person comes into a shop and buys the first gift they are offered. They pay for it and run off to another shop. In practice, what the gift actually is doesn't really make a difference. The price is also irrelevant, provided it is not too high. It all depends on the time remaining until Christmas -- the shorter the time, the greater the remorse of the customers, the greater the price they are willing to pay.
All it takes for Hilbert is to look at his watch -- and he knows right away how much his customers can spend. He can easily take advantage of this fact:
He just finds the most expensive gift he can sell to a given customer, and offer it to them. Only now has he realized that he forgot to employ this cunning strategy last year. That's gonna change though!
Nevertheless, Hilbert would like to know how much his business would have flourished, if he had actually used his grand scheme. He's managed to put together a list of people who came to his store, he is however not sure how much money he could have made on them.
Your task (TL;DR)
The input consists of an ascending list of prices of available gifts, and a list of customers' budgets. The list of budgets is in the same order as the customers arrived to the shop -- with a condition that every customer is willing to pay at least as much as the previous one, meaning it is also ascending.
For each customer, find the most expensive gift they are willing to pay for, and output it's price. If no gifts within the budget are available, output a 0.
You get a -40% characters bonus, if the asymptotic time complexity of your algorithm is O(n+m) (rather than the trivial O(n*m)) Where n, m are the lengths of the input lists.
This is code-golf, shortest bytes wins. Standard loopholes are prohibited.
Example
Input:
1 2 2 2 5 7 10 20
1 1 2 3 6 6 15 21 21 22

Output:
1 0 2 2 5 2 10 20 7 0

This task was taken from a local programming competition, and translated to English by me. Here is the original assignment: https://www.ksp.sk/ulohy/zadania/1131/

Bonuses are one thing to avoid when writing challenges. However, I think it might be fine here. If you want to keep it, I recommend changing it to a percentace based bonus. A 20 character bonus doesn't mean anything to a Java submission, but is basically mandatory for solutions in a golfing language.

Can I award a bounty to OP for the backstory alone? Honestly, that made me smile; every challenge needs one of those.

@tac Thanks, but as is noted in the small text at the bottom, I didn't actually make up the backstory - I only translated it.

@sammko yes, I saw that, but my above comment still holds :)

Pyth, 17 16 bytes
1 byte thanks to Pietu1998
VE=.-Q]
e|fgNTQ0

Demonstration
Explanation:
VE=.-Q]<\n>e|fgNTQ0
                        Implicit: Q is the list of prices.
VE                      For N in the list of budgets
             f   Q      Filter the list of prices
              gNT       On the current person's budget being >= that price
            |     0     If there aren't any, use 0 instead.
          e             Take the last (most expensive) value.
      <\n>              Print it out.
  =.-Q                  Remove it from the list of prices.

I think you can save 1 byte with VE=.-Q]\ne|fgNTQ0. Basically the same thing but with a loop.

Haskell, 67 bytes
a#(b:c)|(h,t)<-span(<=b)a=last(0:h):(init(h++[0|h==[]])++t)#c
_#x=x

Usage example: [1,2,2,2,5,7,10,20] # [1,1,2,3,6,6,15,21,21,22] -> [1,0,2,2,5,2,10,20,7,0].
Split the prices in two parts: (h,t) where h are all prices <= the budget of the next customer and t are all the others. Take the last price of h and continue recursively with all but the last of h plus t and the remaining budgets. last(0:h) evaluates to 0 if h is empty. Similar: init (h++[0|h==[]]) ++ t adds a dummy element 0 to h if h is empty, so that init has something to drop (init fails on the empty list).

Java, 154 * 0.6 = 92.4 bytes
-13 bytes because the lambda can actually use int[], not Integer[] (thanks BunjiquoBianco)
This should take O(n+m) time and O(n+m) additional space (assuming I understand big O notation).
g->b->{int l=g.length,L=b.length,G=0,B=0,A=0;int[]a=new int[l],s=new int[L];for(;B<L;){while(G<l&&g[G]<=b[B])a[A++]=g[G++];s[B++]=A>0?a[--A]:0;}return s;}

Indented: (Try it online!)
static int[] toyStore(int[]g,int[]b) {
    int gl=g.length,bl=b.length,gp=0,bp=0,ap=0;
    int[] a=new int[gl],s=new int[bl];
    for (;bp<bl;) {
        while(gp<gl&&g[gp]<=b[bp])a[ap++]=g[gp++];
        s[bp++]=ap>0?a[--ap]:0;
    }
    return s;
}

public static void main(String[] args)
{
    System.out.println(Arrays.toString(
        toyStore(new int[] {1,2,2,2,5,7,10,20},
                 new int[] {1,1,2,3,6,6,15,21,21,22})
        ));
}

I show the non-lambda expansion here because the type declaration is cleaner and it's the exact same logic. The lambda is present at the ideone link.
Explanation:
Variables used:

g is the list of gift prices, b is the list of budgets.
gl is the length of g and bl is the length of b.
a is a Stack for affordable gifts, s is the output array of sold gifts.
gp, bp, and ap are pointers for g, b, and a respectively. bp is also the pointer for s.

Algorithm:

For each budget in the length of budgets

While this budget can buy the gift at g[gp]

Push the budget onto the Stack a and increment gp

Pop the top of a into s[bp] if it exists, else put 0.

Can't you curry the lambda? (i.e. (g,b)-> to g->b->?

@somebody apparently, yes. For some reason it's never worked for me before but now it will. 0.o (You saved 0.6 bytes after the bonus.)

You can save some bytes by using longs if the input is assumed to be long[] (takes you to 158bytes)  - https://ideone.com/invHlc

@BunjiquoBianco in fact I can just use int[]. For some reason I was under the impression that since the type arguments take reference types (thus not the value-typed primitives like int) that I needed to use a array of reference types. But I can use an array of int just fine. I'll update once I get a chance.

@CAD97 Ha! Can't believe I didn't make that link...

Haskell, 87 * 0.6 = 52.2 bytes
g s(p:q)d@(b:c)|p<=b=g(p:s)q d
g[]p(b:c)=0:g[]p c
g(s:t)p(b:c)=s:g t p c
g _ _ _=[]
g[]

Completely different from my other answer, because I'm going for the bonus.
The last line (-> g[]) is not part of the definition, but calling overhead. Usage example: g [] [1,2,2,2,5,7,10,20] [1,1,2,3,6,6,15,21,21,22] -> [1,0,2,2,5,2,10,20,7,0].
Works basically in the same way as @CAD97's answer, i.e. uses a (initially empty) helper stack to keep track of the buyable items. In detail: check in order:

if the first price is less or equal than the first budget, move the price  to the stack. Call again.
if the stack is empty, return a 0 followed by a recursive call with the budget dropped.
if both stack and budget list are not empty, return the top of stack followed by a recursive call with stack & budget popped.
else return the empty list.

This works in m+n time, because a) operations on the helper stack use constant time and b) in each of the recursive calls one of the lists is shortened by one element.

Jelly, 15 bytes
ṀṄ;©®œ^
Rf@€ç/Ṁ

Try it online!
How it works
ṀṄ;©®œ^  Helper link. Arguments: G, H (lists of affordable gifts)

Ṁ        Compute the maximum of G (0 if the list is empty).
 Ṅ       Print it.
  ; ®    Concatenate it with the register (initially 0).
   ©     Save the result in the register.
     œ^  Compute the multiset symmetric difference of the updated register and H.

Rf@€ç/Ṁ  Main link. Arguments: B (budgets), P (prices)

R        Range; replace each t in B with [1, ..., t].
 f@€     Intersect the list of prices with each budget range, obtaining, for each
         customer, the list of all gifts he's willing to pay for.
    ç/   Reduce the array of lists by the helper link.
         In each iteration, this computes and prints the most expensive gift for
         a customer, than removes the selected gift (and all previously
         selected gifts) from the next list.
      Ṁ  Compute the maximum of the resulting list, which corresponds to the last
         customer.

JavaScript, 85 * 0.6 = 51 bytes
f=(a,b,s=[],[t,...u]=a,[v,...w]=b)=>v?t<=v?f(u,b,[...s,t]):[s.pop()|0,...f(a),w,s)]:[]

Another clone of @CAD97's answer.


text:
Child Genotypes
The Challenge
Everybody loves genetics, right? In this challenge, you will be given the genotypes of two parents. You must find each possible genotype of a child produced by the parents. You must account for dominant and recessive alleles as well as incomplete dominance and codominance.
An example input for the parents could be:
R'RxRr

Parent one (on the left) has a incompletely dominant R allele and a dominant R allele. Parent two (on the right) has a dominant R allele and a recessive allele.
Each parent is separated from the other by an x. The input will not contain an x allele.
An incompletely dominant allele will be followed by an apostrophe ('). Codominant alleles just refers to multiple different types of alleles combined together (A and W for example).
Rules

Shortest code wins (measured in bytes).
Each possibly genotype must be separated from the other genotypes by a comma.
Phenotypes don't matter.
Any letter can be used in the input except for x (which differentiates the parents).
Duplicate genotypes should only be printed once.

Duplicates contain the exact same letters of the same case and type of allele. IF you have WY and YW in your answer, they are considered duplicates.

No more than three different letters will be used in one input.
The order of the letters in the output does not matter.
Answer can be in the form of a string or an array.

Examples
Input 1 (the previous example):
R'RxRr

Output 1:
R'R,R'r,RR,Rr

Alternate output 1 (array):
{R'R,R'r,RR,Rr}

Input 2:
RWxRR

Output 2:
RR,WR
//Or an array, whichever you want

Input 3:
WYxY'y

Output 3:
WY',Wy,YY',Yy
//Once again, an array is fine

Can the output be an array?

Sure. I'll add that to the rules.

http://codegolf.stackexchange.com/questions/76428/all-possible-ways-to-interleave-two-strings duplicate, flagged as

@KennyLau Are you sure? I don't see how they're all that similar.

Well, the only difference is that the "characters" can be two units long.

@KennyLau No, this challenge has a few more requirements; for example, it requires you to take dominant and recessive alleles into account. ("You must account for dominant and recessive alleles as well as incomplete dominance and codominance.") The other challenge seems simpler.

I think it just requires you to remove duplicate.

@NuffsaidM8 Can you add some examples of dominant/recessive allele test cases which can demonstrate that it's not just a simple case of "removing duplicates" as Kenny alludes to? It would also allow people to more easily verify that their code meets all the corner cases.

Welcome to Programming Puzzles & Code Golf Stack Exchange! This is a nice first challenge.

@Chris example two demonstrated duplicates. When you cross the parents, RW and RR would appear twice each. The challenge requires that you only print each once, as shown in the output.

@NuffsaidM8 That's just removing duplicates after doing a Cartesian product. Is there an example where a deduplicated Cartesian product is not an adequate solution?

I think you need to explain the problem more clearly. Does lowercase stand for recessive? What are codominant alleles? Why does the output of the first case have three results?

@Chris Not that I can think of, all the challenge requires is removing those duplicates. To answer your questions don, a lowercase letter always stands for a recessive allele, you can easily Google codominance to get an explanation and the outputs will only have less than three outputs if one of the output is duplicated, in which case you must remove one of the two

It's my biology class, all over again.

Pyth, 20 18 bytes
{msSd*Fc:z".'?"1\x

Test suite.
         z          get input
        : ".'?"1    regex match for any character followed by an optional '
       c        \x  chop on the element "x", resulting in [["R'","R"],["R","r"]]
     *F             splat over Cartesian product, resulting in pairs of "genes"
                      from the first "parent" and from the second
 m  d               map over each resulting pair...
   S                sort (so that we can dedup later)
  s                 concatenate
{                   remove duplicates

JavaScript (ES6), 114 112 104 90 88 bytes
f=>(c=new Set,[z,y]=f.split`x`.map(b=>b.match(/.'?/g)),z.map(e=>y.map(g=>c.add(e+g))),c)

Thanks to Doorknob, Downgoat, Kenny Lau and Neil for helping me golf this down a bit :)

The \w can be replaced by . (because there will not be ψ')

... which means you can shorten the regex to /.'?/g (note the removed i flag, which was unnecessary in the first place), the one I used in my answer.

The i (case-insensitive) tag can be removed as well (as well as the g global tag?).

Thanks guys! @KennyLau, you can't take the g flag off, otherwise it results in undefined

This fails for ABxAB, since AB and BA are identical.for the purposes of the challenge.

You don't need the ()s for a single argument to a => function. a is unused and can be removed. You can also use c.push(x,y) instead of c.concat([x,y]), but it might turn out shorter to map over d[1] or simply to add them directly to the Set.

Your inner Code Reviewer must be at war with yourself

You maybe able to do [z,y]= instead of d=, and then use z instead of d[0] and y instead of d[1] but I'm unsure if it saves any bytes

Ruby, 82 77 bytes
Anonymous function, takes the input string as its argument.
Edited to properly account for ABxAB.
-5 bytes from @Doorknob.
->g{a,b=g.split(?x).map{|s|s.scan /.'?/}
a.product(b).map{|s|s.sort*""}.uniq}

.map(&:sort).uniq.map &:join is shorter as .map{|x|x.sort*''}.uniq.

Nice! I learned a new Ruby shorthand today!

Python 3.5 - 196 bytes:
def b(r):import itertools,re;r=[];[r.append(h)for h in itertools.permutations(re.sub("(?<=[a-zA-Z'])(?=[a-zA-Z])",' ',r.replace('x','')).split(' '),2)if h[::-1]not in r and h not in r];return r

A nice one liner, using some regular expressions.
Note: Around each letter with an apostrophe are double quotes, and I hope that's okay (e.g., in the output, R' would come out as "R'"). Also, for the last test case, it returns [('W', "Y'"), ('W', 'y'), ('Y', 'W'), ('Y', "Y'"), ('Y', 'y'), ('y', "Y'")] instead of just WY',Wy,YY',Yy. I also hope that is okay. If any of these conditions are an issue, just let me know, and I will fix them.

YW and WY are considered duplicates for this challenge, and it is therefor against the rules to print both of them. I have added a bit of clarification to the rules to avoid this in the future.

@NuffsaidM8 Actually. If you look closer, one of them is W,"Y'", whereas the other is just Y,W. Like I said in my answer, those letters with an apostrophe in front of them will have a pair of quotes around them, so the "duplicates" you are talking about are not really duplicates. One of them is incomplete dominance, whereas the other signifies codominance.

I apologize, I was looking at the second and third output yet completely ignored the fact that one is a dominant y and one is recessive!