Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 . 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.

share|improve this question
1  
Is it allowed to use inetd/xinetd or similar? – Digital Trauma Mar 28 at 18:17
79  
I like this, since it's a golfing challenge that golfing languages are unlikely to be very good at. – isaacg Mar 28 at 18:54
6  
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. – MonkeyZeus Mar 29 at 19:50
8  
@isaacg It's only time before someone finds the TCP server built-in in Mathematica – Upgoat Mar 29 at 22:19
2  
@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 – Luaan Mar 30 at 9:11

35 Answers 35

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.

share|improve this answer
17  
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. – Alex A. Mar 28 at 16:43
    
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. – manatwork Mar 28 at 17:02
2  
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. – Alex A. Mar 29 at 4:11
1  
@AlexA. At least I think my question says so. Should I clarify it? – Hannes Karppila Mar 29 at 15:30
    
@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… – manatwork Mar 29 at 15:55

Ruby 2.3, 76 + 7 = 83

Golfed v1 (76)

Socket.tcp_server_loop$*[0]{|c,a|c.puts eval a.ip_address.tr'.',?+;c.close}

Golfed v2 (134, without stdlib TCP server)

(s=Socket.new 2,1).listen s.bind Socket.sockaddr_in$*[0],'127.0.0.1'
loop{->c,a{c<<`bc<<<#{a.ip_address.tr'.',?+}`}[*s.accept].close}

v1 Ungolfed

port = ARGV[0]

Socket.tcp_server_loop(port) do |client, addrinfo|
  ipv4_addr_str = addrinfo.ip_address
  sum = eval ipv4_addr_str.tr('.', '+')
  client.puts(sum)
  client.close
end

v2 Ungolfed

port = ARGV[0]
host = '127.0.0.1'
socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM)
addrinfo = Socket.pack_sockaddr_in(port, host)

socket.bind(addrinfo)
socket.listen(0)

loop do
  client, addrinfo = socket.accept
  remote_ip_address = addrinfo.ip_address
  sum = `bc<<<#{remote_ip_address.tr'.',?+}`

  client << sum
  client.close
end

Output

$ ruby -rsocket server 1234 &
$ nc localhost 1234 -4
128
share|improve this answer
3  
You can replace the .split + .map + .reduce calculation with eval c.addr[-1].tr ?.,?+. By the way, why the regular expression thing? In .addr[-1] I get only the IP address. – manatwork Mar 28 at 16:05
1  
@manatwork That's a good idea if you can guarantee a simple numerical IP address like '127.0.0.1', but c.addr[-1] returns '::ffff:127.0.0.1' for me when I hit it from localhost. – Jesse Sielaff Mar 28 at 16:10
1  
Oh, so that is the reason. I have absolutely no IPv6 configuration here so without you would never find out there can be such additional stuff. Thanks, @JesseSielaff. – manatwork Mar 28 at 16:14
    
@manatwork your eval hack still works on the regex'd string. I updated the answer to use it. – Jesse Sielaff Mar 28 at 16:25
4  
Welcome to Programming Puzzles & Code Golf! This is a great first answer. – Alex A. Mar 28 at 16:40

C#, 284 283 282 278 274 bytes

class A{static int Main(string[]a){var b=new System.Net.Sockets.TcpListener(int.Parse(a[0]));b.Start();for(;;)using(var c=b.AcceptTcpClient())using(var d=new System.IO.StreamWriter(c.GetStream())){var e=c.Client.LocalEndPoint.Serialize();d.WriteLine(e[4]+e[5]+e[6]+e[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:

share|improve this answer
6  
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. – raznagul Mar 29 at 9:45
    
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 Mar 30 at 8:53
    
@Luaan Yeah, that was left over from debugging. – LegionMammal978 Mar 30 at 10:17
    
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 Mar 30 at 11:13
    
@Luaan I need to explicitly Flush the StreamWriter to make it work properly. – LegionMammal978 Mar 30 at 11:16

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
share|improve this answer
2  
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. – Mwr247 Mar 30 at 0:08
    
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? – SpeedyNinja Apr 2 at 19:07

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
share|improve this answer
1  
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). – Donal Fellows Mar 30 at 23:06
    
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... – Olivier Dulac Mar 31 at 17:22
    
proc s {c a p} do you really need all that whitespace? – cat Apr 8 at 13:41

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.
share|improve this answer
1  
.toInteger()as int and s.inetAddress.address*.toInteger()(s.inetAddress.address as int[]). And there is an extra space after .with. – manatwork Mar 28 at 17:33
    
@manatwork thx! Updated. – Will P Mar 28 at 18:13

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.

share|improve this answer
2  
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(".","+"))). – Hannes Karppila Mar 28 at 12:35
1  
@HannesKarppila oh, thanks. forgot about the spaces, the eval hack is pretty cool though. – sammko Mar 28 at 12:40
2  
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). – Skyler Mar 28 at 17:49
1  
can't you just do socket() and therefore save another byte? – Foon Mar 28 at 18:42
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(".","+"))`) – Blender Mar 29 at 23:40

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.
share|improve this answer
1  
Remove the int k= and replace the k with all the c things in Integer.toString(k). To save a few bytes. – GiantTree Mar 28 at 13:40
1  
Javas byte pretty sure messes up the return value for 192.168.2.1 or similar adresses with a byte above 127. – AlexR Mar 28 at 17:06
1  
Change interface to class should gain few more byte – ortis Mar 29 at 8:37
2  
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") – ortis Mar 29 at 9:17
2  
Isn't try(Socket a=...){} shorter than a.close();? Requires Java 7, but can gain bytes. – ogregoire Mar 29 at 14:53

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()}}
share|improve this answer
2  
But it sure is a nice language for making a tcp server! – Numeri Mar 29 at 20:52
1  
Odd, am getting the result 360 when I connect from 192.168.0.67, rather than 427. – steve Mar 29 at 21:43
3  
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. – steve Mar 29 at 21:49
1  
Few more bytes shaved off pastebin.com/HY84sazE - starting to look a bit more "golfed" now – steve Mar 30 at 20:32
2  
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. – Kristoffer Sall-Storgaard Mar 31 at 12:10

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.

share|improve this answer
2  
"Leaks memory and system handles like crazy" What, do you have to free() them after? delete[], maybe? :P – cat Mar 28 at 15:25
7  
@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. – TimmyD Mar 28 at 15:27
    
Oh, isn't PS GC'd? Or does the GC do refcounting and not scope-analysis? – cat Mar 28 at 15:28
    
@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. – TimmyD Mar 28 at 15:40
1  
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 Mar 28 at 16:21

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                     
                 )))
share|improve this answer
    
Yay for Common Lithp! – cat Apr 8 at 13:43

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

$
share|improve this answer

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 screenshot

Edit 2: wget as client

$ wget -qO- localhost:8080
128
share|improve this answer
    
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? – Mikael Mar 29 at 20:36
    
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. – Alex A. Mar 30 at 5:13
    
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. – manatwork Mar 30 at 7:19
    
@Alex A. Thank you and yes, 56-byte solution is under test2.php :) – Mikael Mar 30 at 14:48
    
@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 Mar 30 at 14:48

LiveScript, 107 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 a curried binary function (that adds its operands). Also a bit dirty: /, if given a literal string on its right, will do split.

share|improve this answer

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.
$
share|improve this answer
    
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/\./+/gy/./+/. – manatwork Mar 28 at 18:08
    
Ahh, misread..will revise accordingly and incorporate your good y/ suggestion. – steve Mar 28 at 18:22
1  
while(1){…}{…;redo} according to user130144's great tip. And excepting the ->send() call, all other parenthesis are unnecessary. – manatwork Mar 29 at 12:36

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.

share|improve this answer

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>

share|improve this answer
    
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). – Frxstrem Mar 29 at 23:36
    
Also, you don't have a trailing newline, which should increase your score by 2 bytes. – Frxstrem Mar 29 at 23:40
    
@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. – Mwr247 Mar 30 at 0:05

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?

share|improve this answer
    
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. – Actorclavilis Apr 6 at 0:10

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.

share|improve this answer

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.

share|improve this answer
    
@TimmyD - Ah, you're correct. Missed that on reading through the requirements. Will edit posthaste. – zmerch Apr 4 at 21:43

PowerShell, 208 206 192 152 bytes

($t=[net.sockets.tcplistener]$args[0]).start();for(){($z=$t.acceptsocket()).sen‌d([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

share|improve this answer
    
@TimmyD ah oops I missed that that was necessary... fixed now – Nacht Mar 30 at 21:27
    
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. – Nacht Mar 31 at 12:27
    
fair enough. fixed again – Nacht Mar 31 at 13:29
    
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.coun‌​t,0);$z.close()} – TimmyD Mar 31 at 13:46
1  
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()).sen‌​d([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. – TessellatingHeckler Apr 8 at 0:06

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.
share|improve this answer
1  
You can just post a hexdump of the compiled output for 148 bytes – cat Apr 8 at 13:37
    
Is that allowed? It would make this entry a bit more competitive... – user5434231 Apr 8 at 19:56
1  
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. – user5434231 Apr 8 at 20:17
1  
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. – user5434231 Apr 9 at 15:54
1  
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) – user5434231 Apr 9 at 16:39

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]

share|improve this answer
3  
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. – Hannes Karppila Apr 1 at 10:15

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.

share|improve this answer

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)

share|improve this answer
1  
Only Lua 5.2 and up support labels, if you're curious – Trebuchette Mar 31 at 3:25
1  
Also, Lua automatically casts strings to numbers with the + operator, so you can take out tonumber. – Trebuchette Mar 31 at 3:32

Java, 283 274 bytes

Golfed

import java.net.*;class A{public static int 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 int 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

share|improve this answer
    
Much more elegant than mine. – Matthew Smith Mar 29 at 10:06
    
Use 255 instead of 0xff. Otherwise, same remarks as Matthew's answer. – ogregoire Mar 29 at 14:57

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 head 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.

share|improve this answer
    
Can you use 10 base> instead of string>number? – fede s. Apr 9 at 18:24
    
@fedes. Wow, I never knew that existed. I think that will allow me to shorten a lot of my Factor answers! – cat Apr 9 at 18:30
    
And 10 >base for number>string, also. – fede s. Apr 9 at 18:30
1  
@fedes. Those deserve an answer here :D – cat Apr 9 at 18:32

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.

share|improve this answer
    
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... – Jules Mar 31 at 15:49
    
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. – Jules Mar 31 at 16:04
    
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? – cat May 2 at 2:21

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
share|improve this answer
2  
This doesn't take the listening port as input. – TimmyD Mar 30 at 12:32

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.